problem with fread/fwrite

Siva Chelliah siva at bally.Bally.COM
Wed Nov 7 05:21:54 AEST 1990


I have an interesting (?) question.  

Program 1 : 

#include "stdio.h"
char buf[7];
main ()
{
  int i=1;
  FILE *fp;
  fp = fopen("temp.dat","ab");
  for (i = 0;i<5;i++){
     sprintf(buf,"line %d",i);
     fwrite(buf,sizeof(buf),1,fp);
  }
  fclose(fp);
}
   
temp.dat : 

line 0line 1line 2line 3line 4


fread should update the  pointer, so that I should be able to do a read or 
a write after that. Right ?

Program 2 :

#include "stdio.h"
char buf[7] = "line 4";
char tbuf[7];
main ()
{
  int i=1;
  FILE *fp;
  fp = fopen("temp.dat","r+b");
  fread(tbuf,sizeof(tbuf),1,fp);
  printf("tbuf = %s\n",tbuf);     /* this worked . I got line 0 */
  fwrite(buf,sizeof(buf),1,fp);
  fclose(fp);
}

temp.dat : 

line 0line 1line 2line 3line 4line 0line 4

Can you believe this?  This happened when I used IBM RT, AIX 2.0
When I used Microsoft C 5.1(DOS 3.3 ) , nothing changed in temp.dat .
When I used fseek before fwrite , it worked.  I do not remember reading 
anywhere that I should do a fseek before fread/ fwrite.  Is that a bug in the 
compiler or in my head ?  Please help.

Siva



More information about the Comp.lang.c mailing list