开发者

How to delete a certain line in a text file?

开发者 https://www.devze.com 2023-01-29 00:51 出处:网络
Can you help me code a program that deletes a certain line in a text file. I\'m planning to use: fgets to capture a line from text file and store it in an array, but i was confused how does fgets s

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开发者_StackOverflow 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:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct studentinfo{
       char id[8];
       char name[30];
       char course[5];
}s1;
int main(void){
     FILE *stream = NULL;
     stream = fopen("studentinfo.txt", "rt");

     char arr[100];
     int i=0;

    while(!feof(stream)){  
     fgets(arr, 100, stream);
     printf("%s", arr);
     }
     fclose(stream);
/*planning to reopen the stream but will change "rt" to "wt"*/

     getch();
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号