user3716193
user3716193

Reputation: 476

How to append text to a .txt file iteratively in c

I am having difficulties iteratively writing to a .txt file in C.

I need to write out a series of values after each iteration of a for loop so that if I stop my program from running at any point I will not lose the data I have already collected.

The code I have works if I run through my entire loop but if I use the ctrl+c command to stop a program from running because its taking too long my .txt file is empty.

I don't know if this is caused by the ctrl+c command because the file doesn't have a chance to close or not but is there another solutions to this? Should I open the file and close it during each loop iteration and append to the .txt file? I thought that this might cause the previous data written to the .txt file to be overwritten and also cause increased run time.

Heres a very simple example of what I am currently doing, hopefully it illustrates what I am trying to accomplish:

FILE *fp;
fp = fopen("Output.txt", "w");
int a = 0;
int b = 0;
int c = 0;
for(int i=0;i<500;i++)
{
    a = a+1;
    b = b+1;
    c = c+1;
    printf("a = %d\tb = %d\tc = %d\n"); // printing to console
    fprintf(fp,"%d,%d,%d\n",a,b,c); // printing to file
}
fclose(fp);

Upvotes: 1

Views: 3433

Answers (1)

Sinan &#220;n&#252;r
Sinan &#220;n&#252;r

Reputation: 118128

You need to fflush after each fprintf to the file.

If stream points to an output stream or an update stream in which the most recent operation was not input, fflush()shall cause any unwritten data for that stream to be written to the file, and the last data modification and last file status change timestamps of the underlying file shall be marked for update.

That is,

for(int i=0;i<500;i++)
{
    a = a+1;
    b = b+1;
    c = c+1;
    printf("a = %d\tb = %d\tc = %d\n"); // printing to console
    fprintf(fp,"%d,%d,%d\n",a,b,c); // printing to file
    fflush(fp); /* <== here */
}

PS: Whitespace is not a scarce commodity.

Upvotes: 3

Related Questions