Overwrite fails quietly when fopen with r+ in C

  • Thread starter Thread starter Fardad S
  • Start date Start date
F

Fardad S

Guest
/*
I have written this code (prg.c) to test the problem I am having with
following Visual C compiler:
Microsoft Visual Studio Community 2017
Version 15.8.9
VisualStudio.15.Release/15.8.9+28010.2050
Installed Version: Community
Visual C++ 2017 00369-60000-00001-AA642
Microsoft Visual C++ 2017
Microsoft Visual C++ Wizards 1.0
Microsoft Visual C++ Wizards
Microsoft Visual Studio VC Package 1.0
Microsoft Visual Studio VC Package

The output of the follwing code is supposed to be: (and it is with gcc on linux)

num:10 ret:1
num:30 ret:1
==========++
10
##
30
40

But instead it completely ignores the overwrite and only moves the file
pointer and the output comes out as:

num:10 ret:1
num:30 ret:1
============
10
20
30
40

however if the two lines for the first fscanf and printf
are commented, the output becomes:

num:20 ret:1
============
##
20
30
40
Can anyone explain why? (many thanks in advance)
*/


#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int main(void) {
FILE* fptr;
int num,ret, ch;
fptr = fopen("data.txt", "w"); // creating data.txt file: 10\n20\n30\n40\n
for (num = 1; num <= 4; fprintf(fptr, "%d\n", num++ * 10));
fclose(fptr);

fptr = fopen("data.txt", "r+"); // reopening with r+ (I also tried rt+)

// comment the following two lines and overwrite will work!
ret = fscanf(fptr, "%d\n", &num);
printf("num:%d ret:%d\n", num, ret); -

// overwriting 20 (Fails!, file pointer moves with no error and no output)
fprintf(fptr, "##");
fflush(fptr);

ret = fscanf(fptr, "%d\n", &num);
printf("num:%d ret:%d\n", num, ret);

fclose(fptr);
fptr = fopen("data.txt", "r"); // reopening with r
printf("============\n");
while ((ch = fgetc(fptr)) != EOF) putchar(ch); // printing the content of data.txt
fclose(fptr);
return 0;
}

Continue reading...
 
Back
Top