3

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?

GILGAMESH
  • 1,816
  • 3
  • 23
  • 33
  • Not an answer, but a commment... Isn't 26 the ASCII character for end of file (EOF) ? I would look at the runtime. – Joseph Willcoxson Jun 22 '12 at 23:09
  • yes... I totally forgot about that. But my program reads in data which contain all sorts of data, and so it's not REALLY the end of file when I read in 26. – GILGAMESH Jun 22 '12 at 23:15

1 Answers1

9

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.

Community
  • 1
  • 1
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • Yes, that solved my problem! Thank you. I can't accept your answer now, but will do so in 7 minutes when SO allows me to. – GILGAMESH Jun 22 '12 at 23:10