这段代码应该是跳过一行文件,把其他的内容写在另一个文件中,删除原来的文件,并把不同的文件重命名为被删除的文件。这段代码的问题是,在第一个文件之后,即第二个文件,它既没有被删除,也没有用跳过的文件行创建一个新的文件。是否与重命名删除功能有关?
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
这一行
ch1 = getc(lname);
的返回值进行截断。getc
从 int
到 char
. 因此,while循环条件
while (ch1 != EOF)
将永远是真的,因为 EOF
不成其为 char
.
为了解决这个问题,你必须声明 ch1
要有类型 int
而不是 char
.
关于: 这段代码的问题是在第一个文件之后就不工作了,也就是说,第二个文件既没有被删除,也没有用跳过的文件行创建新的文件,问题出在哪里?是否与重命名删除功能有关?
原文件。rep.txt
实际上是被删除了
然而,这个调用。
rep = fopen("rep.txt", "w+");
却创建了一个同名的空文件