Problem with File Recording txt in C ++

1

When I try to write something new in this file, it deletes what was saved before, is always saving on what it had before, can anyone 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);
    
asked by anonymous 15.06.2014 / 18:16

1 answer

4

This behavior makes sense when opening the file with fopen("nome_do_arquivo","w") , you are opening in writing mode . According to 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 it as a new file (discarding the previous content).

To function as you want, I recommend using "a" (append) mode. 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 on cplusplus.com and fopen no opengroup.com .

    
15.06.2014 / 18:28