我有类似的东西:
istream ifs("/path/to/my/file.ppm", ios::binary);
现在,为了检查扩展文件,有必要获取文件的名称。 我正在使用我自己的函数 read :
... readPPM(std::istream& is) {}
可以从 istream& 变量中获取字符串中的/path/to/my/file.ppm 吗?
最佳答案
你几乎肯定确实使用过
std::ifstream ifs(...);
// ^
但是,即使如此,流也不会保留用于打开它的名称:很少需要这样做,并且对于大多数应用程序来说这将是浪费资源。也就是说,如果您稍后需要该名称,则需要保留它。此外,并非所有流都有名称。例如,std::istringstream
没有名称。
如果您无法将流的名称与流分开传递,则可以附加名称,例如使用 pword()
成员:
int name_index() {
static int rc = std::ios_base::xalloc(); // get an index to be used for the name
return rc;
}
// ...
std::string name("/path/to/my/file.ppm");
std::ifstream ifs(name, ios::binary);
ifs.pword(name_index()) = const_cast<char*>(name.c_str());
// ...
char const* stream_name = static_cast<char*>(ifs.pword(name_index()));
流不会以任何形状或形式维护指针,即,通过上述设置,name
需要比 ifs
对象更长寿。如果需要,可以使用各种回调来维护使用 pword()
存储的对象,但这样做并不简单。
关于c++ - 读取 istream 的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21509857/