a wierd file pointer error?

Jasper Horrell jasper@eng.uct.ac.za
Wed Feb 9 05:52:00 GMT 2000


The following simple C code runs correctly under Linux RedHat 5.1, but
not under Linux Redhat 6.1 (have tested on two 6.1 machines). I compile
as:

gcc -o prog prog.c -lm -O2 -Wall

I think the Redhat 6.1 version of gcc is egcs-1.1.2-24 (that is the RPM
name)

Any ideas would be appreciated!
jasper.
jasper@#no_spam#eng.uct.ac.za

========================================

/* Written to show strange bug which causes erroneous output. This
simple
 * program opens a binary file "test.dat" for reading a writing,
 * reads a line, moves the file pointer back by the number of bytes
 * read and then writes the line back to the file again. The screen
progress
 * update frequency seems to affect whether the program performs
correctly or
 * not. Correct operation is indicated by the number of bytes in the
screen
 * progress update being a multiple of the LineByteSize. Note that the
data file
 * will be incorrectly written if incorrect operation. If the bug does
not
 * show itself, try increasing the LineByteSize or updating progress to
screen
 * less frequently.  
 * */


#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

int main (int argc, char *argv[])
{
  FILE *File=NULL;
  unsigned char *Array=NULL;
  long int line, Lines=200, LineByteSize=10000;

  /* Open file for reading and writing */
  if ( (File = fopen ("test.dat", "r+b") ) == NULL ) {
      fprintf (stdout,"ERROR: Input/output file test.dat not
opened!\n");
      exit(-1);
  }
    
  /* Allocate memory */
  Array = (unsigned char *)malloc(sizeof(unsigned char)*LineByteSize);
  if (Array == NULL) {
    fprintf(stdout,"ERROR - in array mem allocation!\n");
    exit(-1);
  }

  /* Process - read a line, move the file pointer back by the number of 
   * bytes read and then write the line again. */
  for (line=0; line<Lines; line++) {
     fread (Array,1,LineByteSize,File);
     fseek(File,-LineByteSize,SEEK_CUR);
     fwrite(Array,1,LineByteSize,File);

     /* changing the 50 below to 1, results in correct operation */
     if (line%50 == 0){
       fprintf (stdout,"Line %ld done (%ld bytes)\n",line,ftell(File));
     }         
  }

  fprintf(stdout,"done!!\n");

  fclose(File);
  free(Array);

  return(0); /* for success */
 
 }  /* End main program */


More information about the Gcc-bugs mailing list