我有一个文件 main.txt,我想删除该文件中的一行,该行包含一个作为参数传递给程序的数字。
我的代码:
FILE *temp = fopen("main.txt","r");
FILE *copy = fopen("temp.txt","w+");
char line[25]; //lines won't be more than this length
while(fgets(line, sizeof(line), temp)!=NULL)
{
char *s;
s = strstr(line, argv[2]));
if(s!=NULL)
continue;
else
fputs(line,copy);
}
fclose(temp);
fclose(copy);
remove("main.txt");
rename("temp.txt", "main.txt");
失败的情况:
目前我的文件有:
echo hello 24224
echo test123 24196
echo bye 13279
当我尝试删除带有 24196 的行时,它不会将最后一行复制到新文件中。使用 ltrace 显示 strstr 返回非 NULL 值后,fgets 得到一个 emty 字符串。我该如何解决这个问题,这里出了什么问题?
__libc_start_main(0x402636, 3, 0x7ffcee2a2078, 0x4036b0 <unfinished ...>
strcmp("unmanage", "unmanage") = 0
fopen("pid1.txt", "r") = 0x19ee010
fopen("temp.txt", "w+") = 0x19ee240
fgets("echo hello 30876\n", 25, 0x19ee010) = 0x7ffcee2a1f60
strstr("echo hello 30876\n", "5785") = nil
fputs("echo hello 30876\n", 0x19ee240) = 1
fgets("echo lame 9047\n", 25, 0x19ee010) = 0x7ffcee2a1f60
strstr("echo lame 9047\n", "5785") = nil
fputs("echo lame 9047\n", 0x19ee240) = 1
fgets("echo trial 5785\n", 25, 0x19ee010) = 0x7ffcee2a1f60
strstr("echo trial 5785\n", "5785") = "5785\n"
fgets("", 25, 0x19ee010) = 0x7ffcee2a1f60
strstr("", "5785") = nil
fputs("", 0x19ee240) = 1
fgets("", 25, 0x19ee010) = 0x7ffcee2a1f60
strstr("", "5785") = nil
fputs("", 0x19ee240) = 1
fgets("", 25, 0x19ee010) = 0x7ffcee2a1f60
strstr("", "5785") = nil
fputs("", 0x19ee240) = 1
fgets("", 25, 0x19ee010) = 0x7ffcee2a1f60
strstr("", "5785") = nil
fputs("", 0x19ee240) = 1
fgets("", 25, 0x19ee010) = 0
fclose(0x19ee010) = 0
fclose(0x19ee240) = 0
remove("pid1.txt") = 0
rename("temp.txt", "pid1.txt") = 0
atoi(0x7ffcee2a320f, 0x403aca, 0, 0x7fde8ca22367) = 5785
kill(5785, SIGTERM) = 0
+++ exited (status 0) +++