0
I’m starting to work with C files and need to do the skeleton of a book registration program, saving the information in a file. My question is whether I should work with the files like this, opening the file at the beginning of the program and closing at the end:
int main(){
int aux=0, menu;
FILE *acervo;
acervo = fopen("acervo.txt", "a+");
do {
system("cls");
printf ("O que você quer fazer? \n 1 – Inserir um novo cadastro \n 2 – Mostrar todos os cadastros \n 0 – Encerrar \n");
scanf ("%d", &menu);
if( menu == 1){
cadastroLivro();
} else if (menu == 2){
printf("Aqui mostra os dados cadastrados (não está pronto). \n");
} else if(menu != 0) {
printf("Erro: opção inválida! \n");
}
} while (menu != 0);
fclose(acervo);
}
Or so, opening and closing each task:
int main(){
int aux=0, menu;
FILE *acervo;
do {
system("cls");
printf ("O que você quer fazer? \n 1 – Inserir um novo cadastro \n 2 – Mostrar todos os cadastros \n 0 – Encerrar \n");
scanf ("%d", &menu);
if( menu == 1){
acervo = fopen("acervo.txt", "a");
cadastroLivro();
fclose(acervo);
} else if (menu == 2){
acervo = fopen("acervo.txt", "r");
printf("Aqui mostra os dados cadastrados (não está pronto). \n");
fclose(acervo);
} else if(menu != 0) {
printf("Erro: opção inválida! \n");
}
} while (menu != 0);
}
I understand that the first option leaves a bigger margin for the file to corrupt, especially when I just want to read it and it is allowing writing, but the second one makes the "program" slow down, so I don’t know what the best practice here.
In all this, it depends, without context you can’t say.
– Maniero
I tried to give the context.. what was missing?
– Thavi Lang
Where is the context?
– Maniero
The idea of your program is that it starts at the beginning of the day and stays running until night or is executed only when it is necessary and closed as soon as the option is executed? The answer will determine whether it is more advisable to open once and close at the end or to open and close each option chosen. I believe that your program will be slower with only an extremely large number of file openings and closures, I do not think it is anything significant with few thousand operations.
– anonimo
It’s just a job, to be open only when the teacher runs the xD code but if I can put it into the thousands then I think opening and closing each action would be a better practice in this case, since even if I imagine a situation where this program would be effectively used, would not reach the house of a thousand requisitions in one day...
– Thavi Lang
@Thavilang The answer solved your question? Do you think you can accept it? See [tour] if you don’t know how to do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site
– Maniero