Store stack in txt file

0

I'm starting in C and I have the following problem. I need to save strings to a txt file sorted in stack, so far so good, however I need it when I open the program again, it keeps stacking always at the top, but it is overwriting what was already stored. I made the code as simple as possible.

Here I store the string in top position.

void getMensagem(void){
    if (topo == maxL){
        printf("Pilha cheia.\n");
    }
    else {
        printf("Digite sua mensagem:\n");
        scanf("%[^\n]s",mensagem[topo]); // Lê String até encontrar o ENTER. 
        setbuf(stdin, NULL);
    }
    empilhar();
}

And then I store it in the .txt file in order:

char empilhar(){
    FILE *arquivo;
    arquivo = fopen(LOG, "r+");
    int aux;

    for(aux = topo - 1; aux != -1; aux--) {
        printf("Na posicao %d temos %s\n", aux, mensagem[aux]); /// visualizar pilha
        fprintf(arquivo,"%s\n",mensagem[aux]);
        rewind(arquivo);
    }
    fclose(arquivo);
    getchar();
}
    
asked by anonymous 04.06.2017 / 16:40

1 answer

0

Being overwritten because you're using r + to open the file, to write at the end of the file and not delete the pre-existing content you need to use the "a" which means append:

file = fopen (LOG, "a");

If you want to have this same function but can do the writing and reading it is recommended to use the command:

file = fopen (LOG, "a +");

    
04.06.2017 / 17:09