To: Daniel Hitt Cc: djgpp AT sun DOT soe DOT clarkson DOT edu Subject: Re: write() followed by read() doesn't seem to work Date: Mon, 13 Mar 95 08:25:41 +0200 From: Eli Zaretskii > I have a program which needs to write() and read() a file. > > It doesn't do this correctly under go32. This is a classic DINU (DOS is not Unix) problem. You are reading the file in (the default) TEXT mode, which has some unexpected peculiarities under DOS. When reading files in TEXT mode, every CR-LF pair is translated to a single `\n' (to pacify every text-processing C program), for example. More to the point, the read() call quits as soon as it sees the ^Z (ASCII 26) character, because these are used by some oldish DOS programs as ``software EOF'' character. That is why you get only a partial read. Solution? Simple: just open() the file in binary mode, thusly: static void open_file(int *fd) { *fd=open(file_name,O_RDWR|O_BINARY|O_CREAT,open_mode); if (*fd<0) { fprintf(stdout,"Failed on attempt to open %s.\n",file_name); exit(-1); } return; } This would also prevent the mapping of \n to CR-LF on output when you write() the file. Btw, this is all explained in the DJGPP FAQ list, section 9.6: 9.6 Q: I'm reading/writing data files, but the data gets corrupted. Q: When I read a file I get only a small portion of it. A: Are your data files binary? The default file type in DOS is text, even for read() and write(). 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. You must tell the system that a file is binary through the "b" flag in fopen(), or O_BINARY in open(), or use setmode() library function. The FAQ list is available as faqNNN.zip from the same place you've got DJGPP (NNN is a version number).