C++ 从 fstream 获取文件名(或路径)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10773391/
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
Getting filename (or path) from fstream
提问by Pavel Oganesyan
Can I get a file name or its path from a fstream
object? I looked through the methods of fstream
and didn't find anything close to it.
我可以从fstream
对象中获取文件名或其路径吗?我查看了 的方法fstream
并没有找到任何接近它的方法。
采纳答案by Nawaz
No, that is not possible, not at least in the Standard conformant implementation of the library.
不,这是不可能的,至少在符合标准的库实现中是不可能的。
The fstream class doesn't store the filename, and doesn't provide any function for retrieving it.
fstream 类不存储文件名,也不提供任何检索它的函数。
So one way to keep track of this information is to use std::map
as:
因此,跟踪此信息的一种方法是将其std::map
用作:
std::map<std::fstream*, std::string> stream_file_table;
void f()
{
//when you open a file, do this:
std::fstream file("somefile.txt");
stream_file_table[&file] = "somefile.txt"; //store the filename
//..
g(file);
}
void g(std::fstream & file)
{
std::string filename = stream_file_table[&file]; //get the filename
//...
}
Or, simply pass around the filename as well.
或者,也简单地传递文件名。
回答by Walter
you may also design a little class which inherits from fstream
and behaves like a fstream
but also stores its file name.
您还可以设计一个小类,它继承自 afstream
并且其行为类似于 afstream
但也存储其文件名。