www.delorie.com/djgpp/v2faq/faq076.html | search |
| Previous | Next | Up | Top |
Q: My program crashes when I read data files, but the same program on Unix works OK.
Q: When I read a file I get only a small portion of it.
Q: I'm trying to open an existing binary file for read/write using the fstream
class, but no mater what I do, the file is always truncated after I write to it...
read
and write
library functions. Text files get their
newlines converted to CR-LF pairs on write and vice versa on read; reading in "text" mode stops at the first ^Z character. Reading binary files as text will therefore
corrupt the data and fail to read all the data you need. You must tell the system that a file is binary through the b
flag in fopen
, or O_BINARY
in
open
, or use the setmode
library function. Note that the above distinction between binary and text files is written into the ANSI/ISO C standard, so programs that rely on the Unix behavior whereby there's no such distinction, are strictly speaking not portable.
You can also use the low-level _read
and _write
library functions which give you the direct interface to the DOS file I/O; they always use binary I/O.
Problems with read/write access to binary files via fstream
class in C++ programs are due to a bug in the GNU iostream library. This bug causes truncation of files, even if you
never write to the file. The library distributed with GCC version 2.8.1 is free of that bug, so upgrade. A workaround is to do something like this:
fstream inFile; int fd = open ("foobar", O_RDWR | O_BINARY); inFile.open (fd);
webmaster donations bookstore | delorie software privacy |
Copyright ⌐ 1998 by Eli Zaretskii | Updated Sep 1998 |
You can help support this site by visiting the advertisers that sponsor it! (only once each, though)