[英]C++ : Closing specific ifstreams in a global vector with just the file name
对于这个项目,我必须在一个函数中打开一个带有 ifstream 的文件。 我写的代码可以在下面看到:
bool FileReader::openFile(std::string fileName) {
std::ifstream inFile;
streams.push_back(std::move(inFile));
if (streams.back().is_open()) {
std::cout << "File Found";
return true;
}
else {
std::cout << "File Not Found";
return false;
}
然后在另一个函数中关闭它。 这是那个空函数:
bool FileReader::closeFile(std::string fileName) {
return false;
}
这两个函数都通过传入文件路径作为参数来工作,并且 ifstreams 存储在全局向量中,因此可以一次打开多个文件
我不明白的是如何仅以文件名作为参数关闭这些流之一。
任何帮助将不胜感激
没有直接和可移植的方法来获取 std::ifstream 的文件名。 您可以使用地图而不是矢量来引用带有文件名的流。
使用 std::unordered_map<> 的示例:
#include <fstream>
#include <string>
#include <unordered_map>
class FileReader
{
// ...
std::unordered_map<std::string, std::ifstream> streams_;
// ...
// attempts to open fie fileName, and adds it to map of streams.
//
// returns:
// - true on success
// - false if file is already opened or could not be opened.
//
bool openFile(const std::string& fileName)
{
if (streams_.find(fileName) != streams_.end())
return false;
auto ifs = std::ifstream{fileName};
if (!ifs.is_open())
return false;
streams_.emplace(fileName, std::move(ifs));
return true;
}
bool closeFile(const std::string& fileName)
{
auto pos = streams_.find(fileName);
if (pos == streams_.end())
return false;
streams_.erase(pos);
return true;
}
};
请注意,与您的示例不同,包含流的变量位于 openFile() 和 closeFile() 都可见的范围内。
没有直接的方法可以获取 std::fstream 的名称。您可以使用映射而不是向量来引用带有文件名的流。
使用 std::unordered_map<> 的示例:
#include <fstream>
#include <string>
#include <unordered_map>
class FileReader
{
// ...
std::unordered_map<std::string, std::ifstream> streams_;
// ...
// attempts to open fie fileName, and adds it to map of streams.
//
// returns:
// - true on success
// - false if file is already opened or could not be opened.
//
bool openFile(const std::string& fileName)
{
if (streams_.find(fileName) != streams_.end())
return false;
auto ifs = std::ifstream{fileName};
if (!ifs.is_open())
return false;
streams_.emplace(fileName, std::move(ifs));
return true;
}
bool closeFile(const std::string& fileName)
{
if (auto pos = streams_.find(fileName); pos != streams_.end())
{
streams_.erase(pos);
return true;
}
return false;
}
};
请注意,与您的示例不同,包含流的变量位于 openFile() 和 closeFile() 都可见的范围内。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.