如何在 C++ 中从 std::ifstream 获取文件路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3022692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How get file path from std::ifstream in c++
提问by Nilesh Shinge
I open a file using std::ifstream
.
我使用std::ifstream
.
I may open file using relative path (file.txt
) or absolute path (C:\test\file.txt
).
我可以使用相对路径 ( file.txt
) 或绝对路径 ( C:\test\file.txt
)打开文件。
As I am passing a string as the file name, I dont know whether it is relative or absolute path.
当我传递一个字符串作为文件名时,我不知道它是相对路径还是绝对路径。
Can anybody tell me how to get absolute path after file has been successfully open using
std::ifstream
?
谁能告诉我如何在使用成功打开文件后获取绝对路径
std::ifstream
?
e.g.:
例如:
std::ifstream file(strFile); // strFile is "file.txt" or "C:\test\file.txt"
I want to get the absolute path after the file was open successfully.
我想在文件成功打开后获取绝对路径。
Thanks,
谢谢,
回答by Alex B
You can't, std::ifstream
does not store this information.
你不能,std::ifstream
不存储这些信息。
What you cando, however, is:
但是,您可以做的是:
- use process' current working directory to compose the absolute path yourself, or
use a library like Boost.Filesystemlibrary to transform between relative and absolute paths.
boost::filesystem::path abs_path = boost::filesystem::complete("./rel/path"); std::string abs_path_str = abs_path.string();
- 使用进程的当前工作目录自行组成绝对路径,或
使用像Boost.Filesystem库这样的库在相对路径和绝对路径之间进行转换。
boost::filesystem::path abs_path = boost::filesystem::complete("./rel/path"); std::string abs_path_str = abs_path.string();
回答by Alex B
The fstream classes have no functionality for accessing or processing the name used to open the file with, and the C++ Standard Library has no filename processing functions - you will have to write the code yourself, or use a third-party library or operating system-supplied functions.
fstream 类没有访问或处理用于打开文件的名称的功能,并且 C++ 标准库没有文件名处理功能 - 您必须自己编写代码,或者使用第三方库或操作系统 -提供的功能。
回答by Michael J
I don't think it is possible for a std::fstream. I did it for a FILE * on Windows (in a non-portable way). See from file object to file name.
我认为 std::fstream 是不可能的。我在 Windows 上为 FILE * 做了它(以非便携式方式)。查看从文件对象到文件名。
Have you considered extending the ifstream with your own class that remembers the file name?
您是否考虑过使用您自己的记住文件名的类来扩展 ifstream?