如何在 C++ 中找到从 ofstream 创建的文件的目录路径?
我想获取使用 ofstream 创建的文件的目录。 我编写的代码类似于
std::ofstream txt("sample.txt", std::ios::binary);
然后我将一些内容写入txt文件,然后调用txt.close()来关闭ofstream。在编写时,我想获取sample.txt文件的位置并将其写入sample.txt。 例如,目录路径如下所示:
/home/usr/Downloads/sample.txt
我想将整个内容保存为字符串,以便可以将其写入sample.txt 文件中。有人可以帮忙吗? 我正在使用 Linux 来编码,并且有一种通用的方法来做到这一点会很好(在 Windows、Linux、Mac 等上工作)。
I want to get the directory of a file which I created using ofstream.
Code I wrote is something like
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).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该查看 Boost.Filesystem 进行便携式路径处理。 C++ 没有太多的路径,因为您可能在没有文件系统的平台上运行。但是,您可以尝试使用 getcwd 并附加 '/' 来获取某些内容输出和文件名之间。 getcwd 不是 C 的一部分,但它在 Windows 上可用 _getcwd - - POSIX 兼容系统将具有规范的
getcwd
。这应该可以工作(但我很确定在某些特殊情况下它不会工作,例如,如果从 UNC 路径等运行)。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.)好吧,在窗户上,我可以帮你。获取工作目录
http://msdn.microsoft.com/ en-us/library/sf98bd4y%28v=vs.80%29.aspx
听起来像是您要找的。
哦哦哦看这里
获取当前目录?
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
sounds like what you're looking for.
OH OH OH look here
What is a cross-platform way to get the current directory?