Yonatan
Yonatan

Reputation: 73

c: fopen and fprint

as I understood, In the next code:

int main () {
    FILE * f1;
    f1 = fopen("f1.txt","a");
    for (i =0 ; i<10;i++) fprintf(f1,"%d ",i);
    fclose(f1);
    f1 = fopen("f1.txt","a");
    for (i =0 ; i<10;i++)   fprintf(f1,"%d ",i);
    fclose(f1);}

I will get in File f1, the next serial: 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9. I didn't understand why. When I close the file, and open it again, it doesn't remember the end file. I expected that the second loop will override the text that was there before, and I will get just 0 1 2 3 4 5 6 7 8 9. So - what happened?

Upvotes: 3

Views: 1570

Answers (3)

FishBasketGordo
FishBasketGordo

Reputation: 23122

You opened the file in append-mode when you passed "a" as the second argument to fopen, so it appended the data.

Upvotes: 1

geekosaur
geekosaur

Reputation: 61369

"a" means append; perhaps you want "w" (write) instead?

Upvotes: 2

thomson_matt
thomson_matt

Reputation: 7691

It's because you open the file in mode "a", which stands for append. The new text gets added to the end of the file.

If you want to write over what's already there, replace the second fopen with:

f1 = fopen("f1.txt", "w");

"w" stands for write, and will replace what's already there with your new text.

Upvotes: 10

Related Questions