JMad
JMad

Reputation: 122

Ifstream stops reading file after a few lines

I am using an ifstream into a stringstream for reading a file but it stops after a couple lines...

string read(string filename)
{
    ifstream inFile;
    inFile.open(filename);
    stringstream strStream;
    strStream << inFile.rdbuf();
    inFile.close();
    string str = strStream.str();
    return str;
}

This code stops after 'zh¬'
I am thinking maybe they are control characters in the ascii table, the first char after it stops is 26.
But i wouldn't think that matters.

Upvotes: 0

Views: 602

Answers (1)

Mark Ingram
Mark Ingram

Reputation: 73625

Your ifstream is being opened in text mode. Try opening the file in binary mode: std::ifstream inFile(filename, std::ios::binary);

A text stream is an ordered sequence of characters composed into lines (zero or more characters plus a terminating '\n'). Whether the last line requires a terminating '\n' is implementation-defined. Characters may have to be added, altered, or deleted on input and output to conform to the conventions for representing text in the OS (in particular, C streams on Windows OS convert \n to \r\n on output, and convert \r\n to \n on input)

  • Data read in from a text stream is guaranteed to compare equal to the data that were earlier written out to that stream only if all of the following is true:
    the data consist only of printing characters and the control characters \t and \n (in particular, on Windows OS, the character '\0x1A' terminates input)

  • no \n is immediately preceded by a space character (space characters that are written out immediately before a \n may disappear when read)

  • the last character is \n

A binary stream is an ordered sequence of characters that can transparently record internal data. Data read in from a binary stream always equals to the data that were earlier written out to that stream. Implementations are only allowed to append a number of null characters to the end of the stream. A wide binary stream doesn't need to end in the initial shift state.

https://en.cppreference.com/w/cpp/io/c#Binary_and_text_modes

Upvotes: 2

Related Questions