delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/09/30/17:45:13

Message-ID: <004801bdecbb$bb65eaa0$7c2f70c3@kgwujunl>
From: "Graeme Fenwick" <gfenwick AT primex DOT co DOT uk>
To: <djgpp AT delorie DOT com>
Subject: Strange problem reading/writing binary files.
Date: Wed, 30 Sep 1998 22:45:35 +0100
MIME-Version: 1.0
X-Priority: 3
X-MSMail-Priority: Normal
X-Mailer: Microsoft Outlook Express 4.72.2106.4
X-MimeOLE: Produced By Microsoft MimeOLE V4.72.2106.4

Hi all!
Firstly, apologies if you've seen this before (I can't work out if posting
to comp.os.msdos.djgpp on my local server results in everyone seeing it or
not- this *is* a moderated group- right?)

Anyway, I've been having what seems like a strange problem with an example
program for an exercise from "A Book on C", compiled with DJGPP.
The program is meant to display the distinction between binary and text
files on MS-DOS systems by writing text (including a CTRL-Z) to a file
called "temp", then reading it back, and displaying it, in both binary and
text mode.
Problem is, that regardless of whether the file is written in text ("w") or
binary ("wb") mode, when it comes to displaying the file, it *always* stops
at the CTRL-Z, regardless of mode.

I've written a test program to display the contents of another binary file
(in this case a program), which does exactly what it should when displaying
the file in text (stops at CTRL-Z) and binary (reads to end) modes. So why
is the example program not doing what I expect it to do?

(Just a thought, but does this have anything to do with DJGPP's Unix-based
origins, since UNIX doesn't have separate text and binary files?)

(Here's the C code for the example, apologies if the formatting is messed
up!).

#include <stdio.h>

int main(void)
{
   char   cntrl_z = '\032';    /* octal escape for control-z */
   int    c;
   FILE   *ifp, *ofp;

   ofp = fopen("temp", "w");    /* !!! TRY CHANGING TO "wb" !!! */
   fprintf(ofp, "%s%c%s\n",
      "A is for apple and ", cntrl_z, "alphabet pie.");
   fclose(ofp);
   ifp = fopen("temp", "r");                               /* open as text
file */
   while ((c = getc(ifp)) != EOF)                                   /*
display */
      putchar(c);
   fclose(ifp);
   printf("\n---\n");                                   /* serves as marker
*/
   ifp = fopen("temp", "rb");          /* open as binary file */
   while ((c = getc(ifp)) != EOF)                       /* display */
      putchar(c);
   fclose(ifp);
   return 0;
}


--
Graeme Fenwick - gfenwick AT BYESPAMprimex DOT co DOT uk
  (Remove "BYESPAM" spam filter when replying by mail)


- Raw text -


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