What is wrong?

Bill Svirsky svirsky at ttidca.TTI.COM
Thu Jan 26 03:57:38 AEST 1989


In article <2051 at ndsuvax.UUCP> numork at ndsuvax.UUCP (James Mork) writes:
+ #include <stdio.h+ 
+ main(){
+   FILE *fi, *ji;
+   int i,j;
+   fi=fopen("b:newtest.fil","w");
+   for(i=0; i<200; i++) {
+     j=putc(i,fi);
        ^
+     printf("putting %d %d\n", i,j);};
+   i=fclose(fi);
+   printf("opening file for read...\n");
+   ji=fopen("b:newtest.fil","r");
+   for(i=0; i<200; i++) printf("i = %d  (read) = %d\n",i,getc(ji));
                                                          ^
+   i=fclose(ji);
+ };
+ ---
+   I am using TC 1.5 everything was going OK... Now... when I run
+   a simple program like this, the file gets truncated after 25 or
+   26 bytes...    After 25 when I read the file back in, I just
+   get EOF (-1).  What is wrong?  Is this just some error that
+   I am staring at, or is my compiler in foo bar land?

A couple of problems.  putc and getc should be fputc and fgetc
respectively.  I imagine you copied those wrong, otherwise I don't see
how your program would have worked at all.  As to why your program stops
reading after 26 bytes, that is a little more subtle.  It just so
happens that MS-DOS uses ^Z (hex '1A', decimal 26) as it's EOF marker
when doing file I/O in TEXT mode.  Since you are opening the file to
read in TEXT mode (it is the default), MS-DOS returns EOF when it sees
it.  Either fopen the file as "rb" for BINARY mode, or set the global
variable _fmode to O_BINARY.  See the manual page for fopen.  You should
also fopen the output file in BINARY mode as "wb", because MS-DOS also
translates CR to a CR/LF combination when writing in TEXT mode and CR/LF
to a CR when reading.  See _fmode in your manual. 
-- 
Bill Svirsky, Citicorp+TTI, 3100 Ocean Park Blvd., Santa Monica, CA 90405
Work phone: 213-450-9111 x2597
svirsky at ttidca.tti.com | ...!{csun,psivax,rdlvax,retix}!ttidca!svirsky



More information about the Comp.lang.c mailing list