www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1995/03/13/02:09:25

To: Daniel Hitt <hitt AT cs DOT stanford DOT edu>
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 <eliz AT is DOT elta DOT co DOT il>

> 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).

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019