Problem with Saving txt File to C++

Asked

Viewed 131 times

1

Every time I try to record something new in this file, it erases what was saved before, it keeps saving on top of what it had before, someone can tell me what it is?

arquivo = fopen("dados.txt","w");
aux     = x.retorne_energia();
aux2    = x.retorna_nome();
fprintf(arquivo,"%d\t",aux);
fputs(aux2.c_str(), arquivo);
aux     = y.retorne_energia();
aux2    = y.retorna_nome();
fprintf(arquivo,"\n%d\t",aux);
fputs(aux2.c_str(), arquivo);
fclose(arquivo);

1 answer

4


This behavior makes sense when opening the file with fopen("nome_do_arquivo","w"), you are opening in mode writing. According to the documentation:

write: Create an Empty file for output Operations. If a file with the same name already exists, its Contents are discarded and the file is treated as a new Empty file.

That is, if the file already exists, it treats as a new file (discarding the previous content).

To work as you wish, I recommend using the mode "to" (append). In this mode, if the file already exists it positions the cursor to the end of the file. Otherwise the file is created.

Take a look at fopen in cplusplus.com and fopen in opengroup.com.

  • 1

    It worked, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.