Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read long lines from a text file in C++?

Tags:

c++

I am using the following code for reading lines from a text-file. What is the best method for handling the case where the line is greater than the limit SIZE_MAX_LINE?

void TextFileReader::read(string inFilename)
{
    ifstream xInFile(inFilename.c_str());
    if(!xInFile){
        return;
    }

    char acLine[SIZE_MAX_LINE + 1];

    while(xInFile){
        xInFile.getline(acLine, SIZE_MAX_LINE);
        if(xInFile){
            m_sStream.append(acLine); //Appending read line to string
        }
    }

    xInFile.close();
}
like image 602
sonofdelphi Avatar asked May 26 '10 07:05

sonofdelphi


2 Answers

Don't use istream::getline(). It deals with naked character buffers and is therefor prone to errors. Better use std::getline(std::istream&,std::string&, char='\n') from the <string> header:

std::string line;

while(std::getline(xInFile, line)) {
    m_sStream.append(line);
    m_sStream.append('\n'); // getline() consumes '\n'
}
like image 91
sbi Avatar answered Oct 17 '22 04:10

sbi


Since you're using C++ and iostream already, why not use std::string's getline function?

std::string acLine;
while(xInFile){
    std::getline(xInFile, acLine);
    // etc.
}

And, use xInFile.good() to ensure eofbit and badbit and failbit are not set.

like image 41
kennytm Avatar answered Oct 17 '22 04:10

kennytm