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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:26:41  来源:igfitidea点击:

Getting filename (or path) from fstream

c++file-iofstream

提问by Pavel Oganesyan

Can I get a file name or its path from a fstreamobject? I looked through the methods of fstreamand 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::mapas:

因此,跟踪此信息的一种方法是将其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 fstreamand behaves like a fstreambut also stores its file name.

您还可以设计一个小类,它继承自 afstream并且其行为类似于 afstream但也存储其文件名。