如何在多个函数中操作 ifstream 对象
How to manipulate a ifstream object in multiple functions
我正在处理一个涉及解析 XML 文档的项目,我需要创建一个处理文件的打开和关闭函数。我有一个类,它有一个 ifstream 对象和两个关闭和打开的函数,它们使用相同的对象。问题是在打开函数中,对象默认是关闭的,直到程序到达关闭函数,它总是返回你没有打开文件,即使有一个文件打开。有没有办法使对象成为全局对象以创建它,以便它可以在两个函数中工作?任何建议不胜感激
class CommandParser
{
private:
std::ifstream inFile;
std::string pathAddress;
...
...
public:
void open(const std::string address);
void close();
void setPathAddress(const std::string newPathAddress);
};
//Defining file
void CommandParser::open(const std::string address)
{
inFile.open(address);
if(!inFile.fail())
{
throw std::runtime_error("Invalid path! n");
}
else
{
setPathAddress(address);
std::cout << "Successfully opened the file ! n";
parseFile();
}
}
void CommandParser::close()
{
if (inFile.is_open())
{
inFile.close();
std::cout << "Successfully closed file! n";
}
else
std::cerr << "You didn't open a file ! n";
}
如果操作失败,则会设置 fail 标志 – 因此,如果您成功打开文件,则不会设置它(除非之前已经设置过(。
所以好的情况是!inFile.fail()
,但你扔那个...相反,您需要:
if( inFile.fail())
// ^ negation dropped!
{
// error
}
else
{
// success
}
或者更简单一点:
if(inFile)
{
// success
}
else
{
// error
}
旁注:您应该通过 const 引用接受字符串(否则,无论如何const
都是没有意义的......
void open(const std::string& address);
// ^
相关文章:
- 为什么在popback()操作之后,它仍然打印完整的矢量
- ifstream什么都没读
- 重载操作程序时出错>>用于类中的字符串 memebr
- 对字符串进行位操作
- 我可以在 C++ 中的函数体之外进行操作吗?
- MPI突然停止了对多个核心的操作
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 对字符数组中的元素执行逐位操作
- 如何在directx/c++中进行平移/缩放操作
- 逐位操作的隐式类型转换
- 为什么一个向量上的多线程操作很慢
- 排序时无法执行交换操作.我做的时候它会崩溃.为什么
- ifstream文件在从行中读取时被清除
- 位移操作和位掩码未检测到重复字符
- 如何进行特定的位操作?
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 字符串操作 - 字符计数
- 此代码中的操作流程是什么?C/C++.
- 如何在多个函数中操作 ifstream 对象
- C++ 如何处理 ifstream 和 char 数组的">>"操作?