Mail Archives: djgpp/1997/02/26/09:02:00
On Wed, 26 Feb 1997, Luke Lee wrote:
> After a looooong debugging, I've found such a problem : INCORRECT
> size written to a file with 'int write(...)' function !!! Could
> this be libc's bug ? Or anything wrong in my program ?
It depends on how you look at it. IMHO, this is no more bug than the
entire DOS text/binary problem. Here's the scoop (for those who didn't
know it already): `WRITE' DOESN'T NECESSARILY RETURN THE NUMBER OF BYTES
ACTUALLY WRITTEN TO THE DISK. What it returns is the number of bytes IT
HAS BEEN ASKED to write, which is different unless you use binary (as
opposed to text) I/O, because text I/O adds a CR character before each LF
character. Since the default I/O mode is TEXT, you need explicitly to
open file in BINARY mode to have `write' report the actual number of
bytes written. But `creat' doesn't let you specify the mode, so you need
to either use `open', or call `setmode' on the handle that `creat'
returns, like so:
fd = open ("newfile1", O_BINARY | O_WRONLY | O_CREAT | O_TRUNC,
S_IRUSR | S_IWUSR);
or so:
fd = creat ("newfile1", S_IRUSR | S_IWUSR);
setmode (fd, O_BINARY);
or even so:
_fmode = O_BINARY;
fd = creat ("newfile1", S_IRUSR | S_IWUSR);
(I suggest the first method, since it makes more clear what's going on.)
The reason `write' reports the size and not the number of bytes actually
written is to not break (Unix-born) programs which think that if the
number isn't the same, some kind of error happened. Programs written for
DOS generally shouldn't depend on `write' returning the number of bytes
on disk, since all the other DOS compilers I know of exhibit the same
bug/feature.
- Raw text -