photon photon - 3 months ago 22
C++ Question

ifstream won't open file

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?

Answer

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.

Comments