3

I would like to start off with this is my first post and I am not doing this as a homework assignment, but rather to just introduce myself to writing in C.

I'm trying to constantly overwrite the file with my for loop, however halfway through the numbers start to go crazy.

Here is the output:

y = 19530

y = 3906

y = 78119530

y = 15623906

y = -1054493078

Can anyone please provide an explanation as to why in the 3rd iteration of the loop, it jumps to 78119530?

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

int main(int argc, char *argv[]){
int x = 19530;
int y;
FILE *buff;
buff = fopen("BUFF.txt","w+");

for(int i = 1; i <= 5; i++){
    fprintf(buff, "%d", x);
    rewind(buff);
    fscanf(buff, "%d", &y);
    printf("y =  %d\n", y);
    y = y/5;
    fclose(fopen("BUFF.txt", "w+"));
    fprintf(buff, "%d", y);

    }

 return 0;
}
J.Doge
  • 31
  • 2
  • 1
    Your program is broken in numerous ways. Why don't you do any error checking? Why do you always print `x` and then read `y`? – fuz Feb 14 '16 at 23:09
  • Nevermind I am an idiot lol. :( – J.Doge Feb 14 '16 at 23:09
  • So I removed fprintf(buff, "%d", x); and rewind(buff); out of the for loop, now my output to the user is correct. However, my output to the file is still incorrect. – J.Doge Feb 14 '16 at 23:14
  • Please show me the update code. I think you also need another `rewind()` between the `fscanf()` and the `fprintf()` as the `fscanf()` call modifies the file pointer as well. – fuz Feb 14 '16 at 23:15
  • My issue was resolved by making the above changes and using freopen as user Paddy stated below, thanks for your help! :) – J.Doge Feb 14 '16 at 23:21

1 Answers1

4

You are leaking file streams. The following line is incorrect:

fclose(fopen("BUFF.txt", "w+"));

What you are doing here is opening the file again, and closing the new stream, leaving the old stream (kept in buff) valid.

You want this:

fclose(buff);
buff = fopen("BUFF.txt", "w+");

Or this:

freopen("BUFF.txt", "w+", buff);
paddy
  • 60,864
  • 6
  • 61
  • 103