Reputation: 421
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 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?)
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.
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();
}
Upvotes: 0
Views: 1252
Reputation: 500257
Well, disk space permitting, I would do the following:
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.
Upvotes: 1