开发者

File I/O from current Windows position C++

I have not yet found a definitive answer about this. I am trying to have access to files in subfolders from my .EXE. When I have asked before, people tell me to use the absolute location i.e. "c:/game/info/" if I wanted to access something in /info/

But it is completely unreasonable for me or anyone to assume that someone is going to use their program from the same directory. What if the user only has a D drive? That sort of thing.

So my question is: how can I access a file in a开发者_开发问答 subdirectory from my executable without relying on the entire path?


Your title says "Windows", so I'll give a WinAPI-specific answer.

On Windows, you can find your application directory with GetModuleFileName(NULL, ...), and PathRemoveFileSpec. Then PathAppend will make the full path to your data files.

Or you can store the data inside you .exe file as Win32 resources, so they never get separated.


Please note that this approach generally works only for read-only access to data files. If you try to write files in your application directory, you might be blocked by ACLs (depending on install location and local security settings of the computer).


Use GetModuleFileName (Retrieves the fully-qualified path for the file that contains the specified module. The module must have been loaded by the current process.)

char strExePath [MAX_PATH];
GetModuleFileName (NULL, strExePath, MAX_PATH);

You'll then need to extract the folder path (someone has already posted how to do that), and combine your path.


Make or use an installer that asks the user where to install the executable and writes that path to the registry in a well-known location for later reference.


if you use:

#include <fstream>

ifstream stream("file");

it will be working. "file" is file in directory with your exe. Of course if you want go up or down in folders hierarchy use "..\file" or "folder\file"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜