tags:

views:

81

answers:

3

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();
}
+2  A: 

If you use the free function in string, you don't have to pass a max length. It also the uses C++ string type.

Matthew Flaschen
+8  A: 

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.

KennyTM
I'd just do "while( std::getline( xInFile, acLine ) ) {}"
Nikko
Kenny, when input fails, this will attempt to process old data in the `// etc.` part. (If the string was local to the function, it would at least be an empty string.) Better use Nikko's idiom. See [my answer](http://stackoverflow.com/questions/2910836/how-do-i-read-long-lines-from-a-text-file-in-c/2911350#2911350).
sbi
+4  A: 

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'
}
sbi
How about this? istream_iterator<string> cursor( xInFile ); istream_iterator<string> endmarker; while( cursor!= endmarker) { m_sStream.append(*cursor); cursor++; }
sonofdelphi
@sonofdelphi: IIUC, this will read _words_, not _lines_ (where a "word" is anything delimited by whitespace). In order for it to read lines, you would have to instantiate `std::istream_iterator` with a type that reads lines, instead of words. It shouldn't be to hard to come up with such a type, but there is none in the std lib.
sbi