0

I think i have a beginners question.

I try to read a file line by line.

The file is in /home/myhomedir and called text.txt . The content of the file is

1
2
3
4

The file has access right for everyone to read and write.

I wanted: open the file and read it one line after another.

So I tried:

#include <cstdlib>
#include <iostream>
#include <fstream> 

using namespace std;

int main(int argc, char** argv) 
{
    try
    {
        ifstream myfile ;
        myfile.open("/home/myhomedir/text.txt", ios::in);
        if(myfile.is_open())
        {
            string line;

            while (getline(myfile, line)) {
               // do nothing, just get a line
               // *
            }
        }
    }
    catch(int ex)
    {
    }

    return 0;
}

The place marked with * is reached (used the debug feature of netbeans). however line is empty and loop seemed to be entered only once.

Like if an empty file is opened.

What am I doing wrong?

6
  • 1
    You are using the try-catch-continue antipattern (unsuccessfully btw). I hope that's just a bad example. Commented Apr 27, 2014 at 11:11
  • Your code works well... Are you sure that your file exists ? Is it the good path ? Commented Apr 27, 2014 at 11:11
  • 2
    Could you add cout << line << endl; to the loop to see if this has to do with the optimizer? Commented Apr 27, 2014 at 11:15
  • I recommend reading How to Debug Small Programs to get a better idea of how to debug this. Commented Apr 27, 2014 at 11:37
  • @dasblinkenlight you are right. Commented Apr 27, 2014 at 13:44

2 Answers 2

1

The reason is, you don't know how to use debugger. I've modified your code:

#include <cstdlib>
#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char** argv)
{
    try
    {
        ifstream myfile ;
        myfile.open("/home/enedil/text.txt", ios::in);
        if(myfile.is_open())
        {
            string line;

            while (getline(myfile, line)) {
                cout << line; // there's my modification
            }
        }
    }
    catch(int ex)
    {
    }

    return 0;
}

The output is

1234

So everything's correct.

Sign up to request clarification or add additional context in comments.

1 Comment

then it seems to be some sort of optimization. The empty loop is only entered once will the output loop is entered multiple times. while ( myfile.good()){getline(myfile, line);} does what i want (dont ask why, the file needs to be read one time without output.)
0

If the content of the file is literally

1 2 3 4

then it has only one line and it is to be expected that "getline" returns false the second time it's called.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.