怎样删除文本文件在C特定行? [英] How do I delete a specific line from text file in C?
本文介绍了怎样删除文本文件在C特定行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如:
50乔治40结果
石灰30 20结果
卡伦10 60
块引用>{做
的printf(\\ nInput玩家名:[1..10]);
与fgets(姓名,10,标准输入);
}输入名称:石灰
然后文本文件将是:
50乔治40结果
卡伦10 60
块引用>解决方案试试这个---
/ * C程序从文本文件中删除特定的行
* /
#包括LT&;&stdio.h中GT;诠释的main()
{
FILE * fileptr1,* fileptr2;
字符文件名[40];
焦炭CH;
INT delete_line,温度= 1; 的printf(请输入文件名:);
scanf函数(%S,文件名);
//打开文件读取模式
fileptr1 = FOPEN(文件名,R);
CH = GETC(fileptr1);
而(CH!= EOF)
{
的printf(%C,CH);
CH = GETC(fileptr1);
}
//倒带
倒带(fileptr1);
(要删除的行\\ n输入行数:)printf的;
scanf函数(%d个,&安培; delete_line);
//以写模式打开新文件
fileptr2 =的fopen(replica.c,W);
CH = GETC(fileptr1);
而(CH!= EOF)
{
CH = GETC(fileptr1);
如果(CH =='\\ n')
{
临时++;
}
//除了行要被删除
如果(温度!= delete_line)
{
//复制文件replica.c所有行
putc将(CH,fileptr2);
}
}
FCLOSE(fileptr1);
FCLOSE(fileptr2);
删除(文件名);
//文件重命名为replica.c原来的名称
重命名(replica.c,文件名);
的printf(\\ N文件被修改后的内容如下:\\ n);
fileptr1 = FOPEN(文件名,R);
CH = GETC(fileptr1);
而(CH!= EOF)
{
的printf(%C,CH);
CH = GETC(fileptr1);
}
FCLOSE(fileptr1);
返回0;
}参考 - http://www.sanfoundry.com/c -program-删除行文本文件/
Example:
George 50 40
Lime 30 20
Karen 10 60
do { printf("\nInput player name:[1..10] "); fgets(name,10,stdin); }
Input name: Lime
Then the text file will be:
George 50 40
Karen 10 60
解决方案Try this---
/* C Program Delete a specific Line from a Text File */ #include <stdio.h> int main() { FILE *fileptr1, *fileptr2; char filename[40]; char ch; int delete_line, temp = 1; printf("Enter file name: "); scanf("%s", filename); //open file in read mode fileptr1 = fopen(filename, "r"); ch = getc(fileptr1); while (ch != EOF) { printf("%c", ch); ch = getc(fileptr1); } //rewind rewind(fileptr1); printf(" \n Enter line number of the line to be deleted:"); scanf("%d", &delete_line); //open new file in write mode fileptr2 = fopen("replica.c", "w"); ch = getc(fileptr1); while (ch != EOF) { ch = getc(fileptr1); if (ch == '\n') { temp++; } //except the line to be deleted if (temp != delete_line) { //copy all lines in file replica.c putc(ch, fileptr2); } } fclose(fileptr1); fclose(fileptr2); remove(filename); //rename the file replica.c to original name rename("replica.c", filename); printf("\n The contents of file after being modified are as follows:\n"); fileptr1 = fopen(filename, "r"); ch = getc(fileptr1); while (ch != EOF) { printf("%c", ch); ch = getc(fileptr1); } fclose(fileptr1); return 0; }
Reference - http://www.sanfoundry.com/c-program-delete-line-text-file/
这篇关于怎样删除文本文件在C特定行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文