读取 istream 的名称

Read the name of an istream

本文关键字:istream 读取      更新时间:2023-10-16

我有这样的东西:

istream ifs("/path/to/my/file.ppm", ios::binary);

所以现在,为了检查扩展文件,有必要获取文件的名称。 我正在使用自己的函数阅读:

... 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()一起存储的对象,但这样做并不简单。