繁体   English   中英

读取一个文件并写入另一个C

[英]Read one file and write to another C

我正在尝试从文件读取并写入临时文件。 但是,我现在陷入无限循环。 下面的函数被递归函数多次调用,该递归函数遍历目录以读取文件。

我的方法是,我将从一个文件中读取每个单词,然后将这些单词读取到另一个文件中。

如果我只打印每个单词,我拥有的功能就可以正常工作。 它打印出所有目录中每个文件中的每个单词。 但是,当我尝试开始写入临时文件(代码已注释掉)时,我陷入了while循环中。

另一方面,如果我只是在测试程序中调用一次函数,那么我只需从当前目录中的一个文件读取并写入临时文件,就可以了。

这就是我所拥有的(传入时的fileName实际上是绝对路径,并且我执行../tmp因此它不会被递归函数捕获):

void fileReadWrite(char *pattern, char *before, char *replace, char *fileName) {
   FILE *file = fopen(fileName, "r");

   if (file != NULL) {
      int ch, word = 0;
      while ((ch = fgetc(file)) != EOF) {
         if (isspace(ch) || ispunct(ch)) {
            if (word) {
               word = 0;
               putchar('\n');
            }
         }
         else {
            word = 1;
            putchar(ch);

            /*
            FILE *f = fopen("../tmp", "wb"); // create and write
            if (f == NULL)
            {    
               printf("Error opening file!\n");       
               exit(1);
            }

            fprintf(f, "Some text"); // Or fprintf(f, ch);

            fclose(f);
            */
         }
      }
      fclose(file);
   }
}

您的代码中没有任何东西暗示无限循环。 但是,如果fileName非常大,则可能要打开和关闭“ .. \\ tmp”数百万次。 正如Joachim Pileborg在评论中指出的那样,您应该在函数开始时只打开一次该文件,然后在结束时再次将其关闭。

如果要说服自己没有陷入无限循环,请在每次迭代中打印出ch的值。

好的,所以我做到了,而且奏效了。 但是我不明白为什么。 有人可以解释吗?

void fileReadWrite(char *pattern, char *before, char *replace, char *fileName) {
   FILE *file = fopen(fileName, "r");
   FILE *f = fopen("../tmp", "wb"); // MOVE HERE

   if (file != NULL) {
      int ch, word = 0;
      while ((ch = fgetc(file)) != EOF) {
         if (isspace(ch) || ispunct(ch)) {
            if (word) {
               word = 0;
               putchar('\n');
            }
         }
         else {
            word = 1;
            putchar(ch);

            /*

            if (f == NULL)
            {    
               printf("Error opening file!\n");       
               exit(1);
            }

            fprintf(f, "Some text"); // Or fprintf(f, ch);


            */
         }
      }
      fclose(file);
      fclose(f); // MOVE HERE
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM