J.Doge
J.Doge

Reputation: 31

Overwriting text file in C

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;
}

Upvotes: 3

Views: 1172

Answers (1)

paddy
paddy

Reputation: 63451

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);

Upvotes: 4

Related Questions