Erase specific line of a text file

0

I need to delete the last line of a text file. It stores the user's coordinates for each line, but when the user requests a ctrl + z , I need to delete the last line.

How can I do this?

    
asked by anonymous 25.04.2015 / 10:22

1 answer

2

The usual way to treat files in C is to make a new file with what you want from the old one. Then delete the old one (or rename it) and rename the new one to the original name.

Anything like

char linha[1000];
FILE *original, *alterado;
original = fopen("original", "r");
alterado = fopen("alterado", "w");
while (fgets(linha, sizeof linha, original)) {
    processalinha(linha);
    fprintf(alterado, "%s", linha);
}
fclose(alterado);
fclose(original);
unlink("original"); // ou rename("original", "original.bak");
rename("alterado", "original");

Of course, there is no error validation in the above code!

    
25.04.2015 / 10:46