Blacklabel
Blacklabel

Reputation: 846

Retaining the value of a variable even after the C program is closed and opened again

I want to save an integer variable, so that it can be retained even after the C program is restarted.

The way is to store it in a file.

But it is just an integer variable. In the file if I write 1000 first and replace it with 12, it saves as 1200, how can I delete the old value which was there in the file and write the new one?

Or some other way other than files exist?

Thanks Pradeep

Upvotes: 0

Views: 700

Answers (4)

Benedict Cohen
Benedict Cohen

Reputation: 11920

Add a \n or some other control character to indicate the end of the number. You can use fscanf to read it back.

Upvotes: 0

DanDan
DanDan

Reputation: 10562

You might want to use the registry for tasks like this. If using Windows.

Upvotes: -2

James McNellis
James McNellis

Reputation: 355069

When you call fopen to open the file stream, use the "w" mode; this opens the file for writing and truncates it.

Upvotes: 4

Puppy
Puppy

Reputation: 146930

You need to truncate the file before writing to it again, this will wipe the contents so you can write the new value.

Upvotes: 1

Related Questions