开发者

How do I find the directory path of a file I created from ofstream in C++?

I want to get the directory of a file which I created using ofstream. Code I wrote is something like

开发者_Go百科std::ofstream txt("sample.txt", std::ios::binary);

Then I write some things to the txt file, then call txt.close() to close the ofstream. While writing, I want to get the location of the sample.txt file and write it on to sample.txt. For example, the directory path would be like this:

/home/usr/Downloads/sample.txt

I want to save that whole thing as string so I can write it into sample.txt file. Can anyone help? I am using linux to code this, and a universal way to do this would be nice(working on windows, linux, mac etc).


You should look into Boost.Filesystem for portable path handling. C++ does't have too much for paths, as you might be running on platforms without a file system. However, you could try to get something with getcwd and appending '/' between the output and your file name. getcwd is not part of C, but it's available on Windows as _getcwd -- POSIX compliant systems will have the canonical getcwd. This should work (but I'm pretty sure there are corner cases where it won't, for instance, if running from UNC paths or so.)


Well on windows, I can give you a hand. Get Working Directory http://msdn.microsoft.com/en-us/library/sf98bd4y%28v=vs.80%29.aspx

 #include <direct.h>

 char cCurrentPath[MAX_PATH];
_getcwd(cCurrentPath,sizeof(cCurrentPath));

sounds like what you're looking for.

OH OH OH look here What is a cross-platform way to get the current directory?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜