Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 935
J.Doge Avatar asked Feb 03 '26 16:02

J.Doge


1 Answers

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);
like image 131
paddy Avatar answered Feb 05 '26 06:02

paddy