忽略我不想在文本文件中复制的字符串

时间:2012-10-31 14:29:22

标签: c linux file

假设我有一个我不想在文本文件中复制的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.20 ip ..但我的问题是temp.txt只有一个ip .. 例如192.168.5.20

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

谢谢..

3 个答案:

答案 0 :(得分: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,并且rename失败,将errno设置为{{ 1}}。

检查
ENOENT

答案 1 :(得分:0)

如果文件temp.txt中只有192.168.5.20,则您甚至没有进入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检查。节省宝贵的时间。

答案 2 :(得分: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");
    }