Store stack in txt file

Asked

Viewed 319 times

0

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

Here I store the string at the 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 store in the file . txt 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();
}
  • The "%[...]" of scanf() does not lead "s" (the [by itself already indicates that you want to read a string).

  • What is the meaning of this Rewind inside the loop?

1 answer

0

Overwriting because you are 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 "a" which means append:

file = fopen(LOG, "a");

If you want to have this same function but can write and read it is recommended to use the command:

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

  • Thank you David. But using its hint, strings are repeating like this: First String Second First String Third Second First String That’s because of the why I use to store the strings from the bottom up in the file.

  • You use @Davi Luis' answer and use two files, one to store the stack strings and one to know how many strings you have in the stack. When opening the program for the first time it tries to read from the file that stores the quantity and finds nothing, so it assumes that it has nothing. As you add, increment variable. When you quit storing the variable in the file, when you return it follows where it left off. Note. The file that stores the amount will be about written every time you write in it.

Browser other questions tagged

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