Search code examples
c++bufferifstreamreadline

How to read lines from a file using the ifstream?


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

    2B,410,AER,2965,KZN,2990,,0,CR2
2B,410,ASF,2966,KZN,2990,,0,CR2
2B,410,ASF,2966,MRV,2962,,0,CR2
2B,410,CEK,2968,KZN,2990,,0,CR2
2B,410,CEK,2968,OVB,4078,,0,CR2
2B,410,DME,4029,KZN,2990,,0,CR2
2B,410,DME,4029,NBC,6969,,0,CR2
2B,410,DME,4029,TGK,\N,,0,CR2

(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);

    try
    {
        // Init stream
        if (!m_ifs.is_open())
            m_ifs.open(".\\Assets\\routes.txt", std::fstream::in);
    }
    catch (int errorCode)
    {
        showException(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)
        m_ifs.close();

    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!

Thanks


Solution

  • 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