如何删除文本文件中的某一行?
你能帮我编写一个删除文本文件中特定行的程序吗?
我计划使用:
fgets 从文本文件中捕获一行并将其存储在数组中,但我很困惑 fgets 如何将行存储在数组中(它是否捕获行并将其存储在第一个数组中)索引,下次它捕获一行时,会将其存储到下一个索引还是只是覆盖数组的第一个索引?)
如果该行存储在不同的索引中,我将有一个条件,将用户的输入与 fgets 捕获的行进行比较,如果相等,它将跳过该行并执行规则,直到到达末尾 如果该行存储在不同的索引中,
然后我将像这样的 fclose(stream) 一样关闭文本文件,并将其重新打开为“wt”以覆盖文件中写入的所有内容。
我的逻辑是否正确...或者您可以提出更好的解决方案... 希望你能帮助我理解 fgets 如何将行存储在数组中...
顺便说一句,这是我正在尝试进行测试的代码:
#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();
}
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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,如果磁盘空间允许,我会执行以下操作:
这可以避免需要将(几乎)整个文件保留在内存中。
它也不会遇到这样的问题:如果您的程序在写入文件的过程中终止(或被终止),则输入文件的一部分可能会永久丢失。
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.