user3219446
user3219446

Reputation: 117

Prevent a file from being recreated or overwritten

Data are stored in the file as it's should,but when i re-launch the program they get vanished, and the file size returns to 0.

Here's what's i came up with so far:

 if (!fp) {
    fp=fopen("data.txt", "wb");
  }

but it's doesn't work.

Thank you!

Upvotes: 0

Views: 201

Answers (5)

Bill Lynch
Bill Lynch

Reputation: 81916

Let's look at the documentation for fopen():

The table from cppreference

We can ignore the b in wb, because it just makes things run in a binary mode.

If we look at the description of w, we can see that it says that it destroys the contents of an existing file with the same name. That's the behavior you are seeing.

Instead of that, you probably want to use rb+ or ab. The rb+ variant will keep the existing data in the file, and set the position in the opened file to point at the beginning. Alternatively. you could use ab which will set the position in the file to the end.

Upvotes: 5

macfij
macfij

Reputation: 3209

see http://man7.org/linux/man-pages/man3/fopen.3.html
if you pass w as mode to fopen, the size of file is truncated to 0. so, everytime you run your program, file that is being opened will lose all the data that you've written on previous execute of program. use a mode instead. the a mode stands for "append" - it will allow you to write data at the end of the file. if file does not exist, it will create it.

Upvotes: 1

wat
wat

Reputation: 1

You need to change your mode.

"w" Create an empty file for writing. If a file with the same name already exists its content is erased and the file is considered as a new empty file.

http://www.tutorialspoint.com/c_standard_library/c_function_fopen.htm

Upvotes: 0

Josan
Josan

Reputation: 722

Depend on what are you going to use the file. Maybe you could look at the append mode of opening a file.

Upvotes: 0

dohashi
dohashi

Reputation: 1841

When your program runs, it overwrites the existing file. Try using

fp=fopen("data.txt", "ab");

Upvotes: 0

Related Questions