ifstream不会打开文件

问题描述:

我想打开一个文件,以便我可以从中读取。ifstream不会打开文件

#include <iostream> 
#include <fstream> 
#include <cstdlib> 
using namespace std; 

ifstream input_file("blah.txt", ios::in); 
ofstream output_file("output.txt", ios::out); 

Bank::Bank(void){ 
    input_file.open("blah.txt"); 
    if(!input_file){ 
     cerr << "Error" << endl; 
     exit(1); 
    } 
    else{ 
     cout << "good 2 go" << endl; 
    } 
} 

这是我用于阅读名为blah.txt的文件的代码,我在终端上得到的输出是“Error”。我使用Linux Mint 14和gVim,所以当我输入:pwd命令时,我知道我在目录/ mnt/share中。从终端检查,文件blah.txt是在同一个目录中。我唯一能想到的就是隐藏的文件扩展名。为什么我无法打开文件?

这是因为你打开“blah.txt”两次。

首播时间:

ifstream input_file("blah.txt", ios::in)

二时间:

input_file.open("blah.txt")

卸下第二个应该解决您的问题。

ifstream input_file("blah.txt", ios::in); 

should open the file

此外,当使用第二个构造形式中,流与物理文件相关联,如同到成员函数的调用以相同的开参数已制定。

input_file.open("blah.txt"); 

should fail

如果对象已经有相关的文件(打开),则操作失败。

请阅读文档。