Microsoft KB Archive/43072

= INFO: Switching from Reading to Writing Files Can Garble Data =

Article ID: 43072

Article Last Modified on 12/12/2003

-

APPLIES TO

 The C Run-Time (CRT), when used with:  Microsoft Visual C++ 1.0 Professional Edition

 Microsoft Visual C++ 1.5 Professional Edition

 Microsoft Visual C++ 1.0 Professional Edition

 Microsoft Visual C++ 2.0 Professional Edition</li></ul>

 Microsoft Visual C++ 2.1</li></ul>

 Microsoft Visual C++ 2.2</li></ul>

 Microsoft Visual C++ 4.0 Standard Edition</li></ul>

 Microsoft Visual C++ 4.1 Subscription</li></ul>

 Microsoft Visual C++ 5.0 Standard Edition</li></ul>

 Microsoft Visual C++ 6.0 Service Pack 5</li></ul> </li></ul>

-

<div class="notice_section">

This article was previously published under Q43072

<div class="notice_section">

<div class="summary_section">

SUMMARY
When switching from reading to writing data files, it is necessary to make a call to 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 &quot;Microsoft C Optimizing Compiler Run-Time Library Reference&quot; manual, which shipped with version 5.1 of the Microsoft C Compiler. The following program attempts to read in the first character of a file and to write it out as the second character:

Sample Code #1
void main(void) { FILE *fp; char a;
 * 1) include <stdio.h>

if (( fp = fopen(&quot;text.fil&quot;,&quot;r+&quot;)) != NULL) {   fscanf(fp,&quot;%c&quot;,&a);      /* Read one character */ fprintf(fp,&quot;%c&quot;,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 to change the pointer position. The following program performs the desired operation:

Sample Code #2
void main(void) { FILE *fp; char a; fpos_t loc;     /* Storage for the current location */
 * 1) include <stdio.h>

if (( fp = fopen(&quot;text.fil&quot;,&quot;r+&quot;)) != NULL) {   fscanf(fp,&quot;%c&quot;,&a);    /* Read one character */ fgetpos(fp,&loc);    /* Get current file pointer pos */ fsetpos(fp,&loc);    /* Set current file pointer pos */ fprintf(fp,&quot;%c&quot;,a);  /* Write to next location */ fclose(fp); } }

Keywords: kbinfo kbcrt KB43072

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.