Guy Leonard Thomas Guy Leonard Thomas - 1 year ago 131
C++ Question

How to read lines from a file using the ifstream?

I have a text file with the following information in it:


(it is airline route info)

I'm trying to loop through the file and extract each line into a char* - simple right?

Well, yes, it's simple but not when you've completely forgotten how to write successful i/o operations! :)

My code goes a little like:

char * FSXController::readLine(int offset, FileLookupFlag flag)
// Storage Buffer
char buffer[50];
std::streampos sPos(offset);

// Init stream
if (!m_ifs.is_open())".\\Assets\\routes.txt", std::fstream::in);
catch (int errorCode)
return nullptr;

// Set stream to read input line
m_ifs.getline(buffer, 50);

// Close stream if no multiple selection required
if (flag == FileLookupFlag::single)

return buffer;


Where m_ifs is my ifStream object.

The problem is that when I breakpoint my code after the getline() operation, I notice that 'buffer' has not changed?

I know it is something simple, but please could someone shed some light onto this - I'm tearing my forgetful hair out! :)

P.S: I never finished writing the exception handling so it is pretty useless right now!


Answer Source

There are two basic problems with your code:

  1. You are returning a local variable. The statement return buffer; results in a dangling pointer.

  2. You are using a char buffer. C-style strings are discouraged in c++, you should always prefer std::string instead.

A far better approach is this:

string FSXController::readLine(int offset, FileLookupFlag flag) {
    string line;
    //your code here 

    getline(m_ifs, line) //or while(getline(my_ifs, line)){ //code here } to read multiple lines
    //rest of your code
    return line;

More information about std::string can be found here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download