类中的Fstream初始化 - 检查文件是否打开

时间:2013-02-05 23:25:05

标签: c++ class exception-handling initialization fstream

示例:

//头文件

class Example
{
    private:
            fstream InputObject;  

    public:
            Example();  

}

//实施档案

Example::Example():InputObject("file_name.txt", ios::in) {}

从我迄今为止从类似问题中读到的内容来看,在C ++的“旧”版本中,用于初始化类中的fstream对象的唯一方法是通过上面显示的成员列表初始化来实现。

问题:
如果这确实是在类中初始化fstream对象的“唯一”方式,那么如果文件无法打开,我们该怎么办?

通常我会通过检查运行fstream对象以确保它正确打开,但在这种情况下似乎不可能。此外,即使我可以,如果第一次没有这样做,我怎么能重新初始化对象呢?

1 个答案:

答案 0 :(得分:0)

#define WIN32_LEAN_AND_MEAN // This makes it so it doesn't look through libs that are not included when running

#include <fstream> //To Read write to files, to be able to
#include <iostream> // The basic stuff, cout, cin, etc.
using namespace std; // the capability of typing cout instead of std::cout
int main() // our main loop
{
fstream InputObject; // declaring InputObject as something that can write to a file
if(!Inputobject.open("File Name Here") // if it cant open the file
{
cout << "File not Open" << endl; // then write to console, " File not Open"
}

return 0;
system("pause");
}

你想知道文件是否打开,所以使用!在打开文件的函数之前,不打开,所以带有!InputObject.open的if语句将检查它是否未打开,如果是,则执行某些操作,因此cout&lt;&lt; “文件未打开”会告诉你它是否打开。