Deleting specific line from a text file

Asked

Viewed 5,806 times

1

I need to delete the last line of a text file. It files user coordinates for each line, but when the user requests a Ctrl + z, I need to delete the last line.

How can I do that?

1 answer

3


The usual way to handle C files 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 one.

Something 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 error validation is missing in the above code!

  • Thanks, solved my problem

  • By the way, this solution does not apply only in C - when you have text files, in any language, the only way to create changes is to write a new file. That’s why when the data volume increases (>100000 lines for example, or depending on the performance needed well before that) - the best thing is to put the data in an SQL database, where each record can be updated/removed independently.

Browser other questions tagged

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