How to delete a certain line in a text file?

Can you help me code a program that deletes a certain line in a text file.

I'm planning to use:

  1. fgets to capture a line from text file and store it in an array, but i was confused how does fgets store the line in an array(does it capture the line and store it in the first index and the next time it captures a line will this be stored to the next index or just overwrite the first index of an array?)

  2. if the line was stored in different indices I'll then have a condition that compares the user's input to the captured line of fgets and if it is equal, it will skip the line and do the rule till it reaches the end of file.

  3. then I'll close the text file like this fclose(stream) and reopen it as "wt" to overwrite everything written at the file.

Am I having the right logic... or you can suggest better solutions... hope you can help me understand how fgets store the line in an array...

btw this is the code I'm trying for my testing:

struct studentinfo{
       char id[8];
       char name[30];
       char course[5];
int main(void){
     FILE *stream = NULL;
     stream = fopen("studentinfo.txt", "rt");

     char arr[100];
     int i=0;

     fgets(arr, 100, stream);
     printf("%s", arr);
/*planning to reopen the stream but will change "rt" to "wt"*/



Well, disk space permitting, I would do the following:

  • open input file for reading
  • open a temporary file (in the same directory) for writing
  • while not at the end of input file:
    • read line from input file
    • if it does not equal the line you're looking for, write it out to the output file
  • close both files
  • remove the input file
  • rename the temporary file to give it the input file's name

This avoids the need to keep the (almost) entire file in memory.

It also does not suffer from the problem that if your program dies (or gets killed) in the middle of writing the file, a part of your input file may be lost for good.

Need Your Help

redeclared as different kind of symbol error in C

c struct typedef

I get the error 'J_TypeInstructions' redeclared as different kind of symbol' in the following C code: