0

假设我有一个不想复制到文本文件中的 ip 列表。这就是我所做的..例如我不想复制192.168.5.20...

在我的 temp.txt 文件中,我有 ip:

192.168.5.20
192.168.5.10
192.168.5.30
192.168.5.50
192.168.5.12

-

char *data = "192.168.5.20";

char buff[100];
FILE *in, *out;

in = fopen("/tmp/temp.txt", "r");

while(fgets(buff,sizeof(buff),in) !=NULL){


        if(!strstr(buff, data)){

        printf("copying to ip.txt\n");
        out = fopen("/tmp/ip.txt", "a");
        fprintf(out,"%s",buff);
        fclose(out);
        }


}
if(feof(in)){

printf("Closing file descriptor and renaming ip.txt to temp.txt\n");
fclose(in);
rename("/tmp/ip.txt", "/tmp/temp.txt");
}

它可以离开192.168.5.20ip.. 但我的问题是 temp.txt 只有一个 ip.. 例如192.168.5.20

现在我想忽略它,所以当我打开 temp.txt 文件时它应该是空白的。但是当我打开我的 temp.txt 文件时,ip 仍然192.168.5.20存在?.. 为什么会这样?

谢谢..

4

3 回答 3

0

/tmp/ip.txt仅当其中至少有一行/tmp/temp.txt不包含要忽略的模式时,才会创建该文件。

if(!strstr(buff, data)){
    printf("copying to ip.txt\n");
    out = fopen("/tmp/ip.txt", "a");
    fprintf(out,"%s",buff);
    fclose(out);
}

因此,如果/tmp/temp.txt仅包含一行,并且包含要忽略的模式,/tmp/ip.txt则创建 no 并rename失败,设置errnoENOENT.

检查与

#include <errno.h>
#include <string.h>

int fail = rename("/home/dafis/Doesntexist", "/home/dafis/doesexist");
if (fail) {
    int en = errno;
    if (en)
        perror(strerror(en));
}
于 2012-10-31T14:51:52.360 回答
0

如果仅192.168.5.20在文件 temp.txt 中存在,则您甚至没有进入 while 循环。这意味着您没有打开(如果不存在则创建)ip.txt。所以重命名失败并且 temp.txt 保持不变。您可以尝试更改您的代码如下

   if (feof(in))
   {
      if(0 == out)
         out = fopen("ip.txt", "a");
      printf("\nrename returned %d",rename("ip.txt", "temp.txt"));

      printf("Closing file descriptor and renaming ip.txt to temp.txt\n");
      fclose(in);
   }

请在代码中添加一些 NULL 检查。节省宝贵的时间。

于 2012-10-31T14:52:46.777 回答
0
char *unwanted = "192.168.5.20";

char buff[100];
FILE *in, *out;
unsigned cnt;

in = fopen("/tmp/temp.txt", "r");
out = fopen("/tmp/ip.txt", "w");

if (!in || !out) exit(EXIT_FAILURE);

for (cnt=0; fgets(buff,sizeof buff,in) ; ){
        if(strstr(buff, unwanted)) continue;
        fprintf(out,"%s",buff);
        cnt++;
        }

fclose(out);
fclose(in);

 /* note: this will maintain the original file if it **only** consists
 ** of lines with the (unwanted) pattern in it.
 ** IMHO you'd better do the rename unconditionally; an empty file
 ** would be the correct result if all the lines match.
 */
if(cnt){ 
    printf("Closing file descriptor and renaming ip.txt to temp.txt\n");
    rename("/tmp/ip.txt", "/tmp/temp.txt");
    }
于 2012-10-31T15:07:58.783 回答