Search code examples
c++visual-studio-2010visual-c++asciivisual-c++-2010

ifstream::read fails at ASCII 26


This problem has been bugging me for a long time. For example, the code

ifstream in;
char temp;
int a;

in.open ("Random.txt");

for (a = 0;a < 10000;a++)
    in.read (&temp, 1);

in.close ();

works fine until the ifstream encounters a substitute character (ASCII = 26). Then, for all following characters, ifstream::read gives me temp = -1. I don't really want this to happen, but instead want it to keep on reading characters from the file instead of -1. What have I done wrong?


Solution

  • You need to open the stream in binary mode. For historic reasons the text mode on Windows will consider Control-Z (ASCII 26) as the end of a file.

    There are more details in this earlier answer of mine.