问题
I'm trying to open a file so I can read from it.
#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;
}
}
This is the code I have for reading the file named blah.txt and the output I'm getting at the terminal is the "Error". I am using Linux Mint 14 and gVim, so when I enter the :pwd command, I know I am in directory /mnt/share. Checking from the terminal, file blah.txt is in the same directory. The only thing I can think of is hidden file extensions. Why can't I open the file?
回答1:
That's because you open "blah.txt" twice.
First time:
ifstream input_file("blah.txt", ios::in)
Second time:
input_file.open("blah.txt")
Removing the second one should fix your problem.
回答2:
This
ifstream input_file("blah.txt", ios::in);
should open the file:
Additionally, when the second constructor version is used, the stream is associated with a physical file as if a call to the member function open with the same parameters was made.
This
input_file.open("blah.txt");
should fail:
If the object already has a file associated (open), the function fails.
Please read the documentation.
来源:https://stackoverflow.com/questions/14920106/ifstream-wont-open-file