【发布时间】:2020-06-08 15:15:15
【问题描述】:
此代码应该跳过一行文件并将其他所有内容写入不同的文件,删除原始文件,并将不同的文件重命名为已删除的文件。这段代码的问题是它在第一个文件之后不起作用,即第二个文件没有被删除,也没有使用跳过的文件行创建新文件。问题是什么?是不是跟rename remove函数有关系?
FILE *lname
FILE *id
FILE *rep
lname = fopen("lname.txt", "r");
id = fopen("id.txt", "r");
rep = fopen("rep.txt", "w+");
char ch1,ch2;
int temp=1,delete_line=3; /*(delete_line is supposed to be taken as an input)*/
ch1 = getc(lname);
while (ch1 != EOF)
{
if (ch1 == '\n')
temp++;
if(delete_line==1) {
if (temp == 2 && ch1 == '\n')
ch1 = getc(lname);
}
if (temp != delete_line)
putc(ch1, rep);
ch1 = getc(lname);
}
fclose(lname);
fclose(rep);
remove("lname.txt");
rename("rep.txt","lname.txt");
rep = fopen("rep.txt", "w+");
ch2 = getc(id);
while (ch2 != EOF)
{
if (ch2 == '\n')
temp++;
//except the line to be deleted
if (temp == 2 && ch2 == '\n') //making sure to skip a blank line if delete_line=1
ch2 = getc(id);
if (temp != delete_line)
putc(ch2, rep);
ch2 = getc(id);
}
fclose(id);
fclose(rep);
remove("id.txt");
rename("rep.txt","id.txt");
id.txt 中的数据
asd123
xcv1323
rijr123
eieir2334
lname.txt 中的数据
Bipul Das
Star Lord
Tony Stark
Vin Diesel
【问题讨论】:
-
您可能想在读取第一个文件后重置
temp=1。 -
stackoverflow.com/questions/62256572/… 专注于pmg评论。您还删除了几乎完全相同的this question - 请编辑您的问题并在下次取消删除它。
-
ch1和ch2是什么类型?它们应该是int。 -
OT:
while循环的代码可以简化一点,例如ch1 = getc(lname);while (ch1 != EOF){if (temp != delete_line)putc(ch1, rep);if (ch1 == '\n')temp++;ch1 = getc(lname);}。 -
OT:关于:
ch2 = getc(id); while (ch2 != EOF)更好地将这两行合并为:while( (ch2 = getc(id) ) != EOF ),并在循环结束时删除对getc()的调用
标签: c gcc file-handling filehandle gcc4.7