INF: Switching from Reading to Writing Files Can Garble Data

ID Number: Q43072

5.10 6.00 6.00a 6.00ax 7.00 | 5.10 6.00 6.00a

MS-DOS | OS/2

Summary:

When switching from reading to writing data files with Microsoft C

versions 5.1, 6.0, 6.0a, 6.0ax, or C/C++ 7.0, it is necessary to do an

fsetpos(), fseek(), or rewind() function. If a call to one of these

functions is not made, the file pointer may not be updated and the

data could be corrupted. It is also necessary to make a call to one of

these functions when switching from writing to reading. This is

documented on page 275 of the "Microsoft C Optimizing Compiler

Run-Time Library Reference" manual, which shipped with version 5.1 of

the Microsoft C Compiler.

More Information:

The following program attempts to read in the first character of a

file and to write it out as the second character:

#include <stdio.h>

void main(void)

{

FILE *fp;

char a;

if (( fp = fopen("text.fil","r+")) != NULL)

{

fscanf(fp,"%c",a); /* Read one character */

fprintf(fp,"%c",a); /* Write to the next location */

fclose(fp);

}

}

The above program fails because there is no fseek, fsetpos, or rewind

between the fscanf and fprintf. The following program performs the

desired operation:

#include <stdio.h>

void main(void)

{

FILE *fp;

char a;

fpos_t loc; /* Storage for the current location */

if (( fp = fopen("text.fil","r+")) != NULL)

{

fscanf(fp,"%c",a); /* Read one character */

fgetpos(fp,&loc); /* Get current file pointer pos */

fsetpos(fp,&loc); /* Set current file pointer pos */

fprintf(fp,"%c",a); /* Write to next location */

fclose(fp);

}

}

Additional reference words: 6.00 6.00a 6.00ax 2.00 2.01 2.50 2.51 7.00

quickc sequence locate position