Jiew Meng
Jiew Meng

Reputation: 88397

C++ File not read?

I want to read a file line by line. Did something like

void Parse (string filepath) {
    ifstream sourceFile;
    sourceFile.open(filepath);
    for (string line; getline(sourceFile, line);) {
        cout << "1" << endl;
        cout << line << endl;
    }
}

int main() {
    Parse("C:\\test.txt");

    getchar();
    return 0;
}

Then put some text into C:\test.txt, but when I run, I dont get anything. Why? Not even the "1". I notice no exception if the file is not there too. I suppose that a sign of a problem?

Upvotes: 1

Views: 183

Answers (3)

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 71009

I think you have problems opening the file. I would suggest two things:

  • check if sourceFile is opened successfully(if (sourceFile))
  • debug the code and see the code path your code follows.

EDIT: adding the actual solution to the problem in my answer(instead of just a comment) so that people won't miss it:

Here is one more thought - check the file name in its properties. Has happened to me that if windows hides the extension of the file the name is actually test.txt.txt, while what I see displayed is only test.txt.

Upvotes: 2

tomahh
tomahh

Reputation: 13661

change your for loop to

for (string line; sourceFile.good();) {
    getline(sourceFile, line);

}

This way, you check the validity of your stream in the conditional part of the for, and get the line if the stream good.

Upvotes: 0

slaphappy
slaphappy

Reputation: 6999

You have to check for success/error manually. Try with ifstream::good():

sourceFile.open(filepath);
if(!sourceFile.good()) {
  // do something

If you don't want to check manually, you can enable exceptions:

// call that before open()
sourceFile.exceptions ( ifstream::failbit | ifstream::badbit );

Upvotes: 3

Related Questions