繁体   English   中英

处理文本文件两个

[英]Working with Text Files Two

关于以下代码,确实有几个问题,我在上一篇文章中从中获得了帮助。

1)。 有什么想法为什么在输出结束时会显示一个随机的垃圾字符? 我正在释放文件等并检查EOF。

2)。 这个想法是,它可以处理多个文件争论,因此我想创建一个递增的新文件名,即out [i] .txt,在C语言中可以吗?

该代码本身获取一个文件,该文件包含所有用空格隔开的单词,例如一本书,然后循环遍历,并用\\ n替换每个空格,从而形成一个列表,请查找以下代码:

#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <stdio.h>

/*
 * 
 */
int main(int argc, char** argv) {

FILE *fpIn, *fpOut;
int i;
char c;
while(argc--) {
    for(i = 1; i <= argc; i++) {
        fpIn = fopen(argv[i], "rb");
        fpOut= fopen("tmp.out", "wb");
        while (c != EOF) {
            c = fgetc(fpIn);
            if (isspace(c)) 
                c = '\n';
            fputc(c, fpOut );
        }
    }
}
fclose(fpIn);
fclose(fpOut);
return 0;
}

当到达文件末尾时,您不会break循环。 因此,您所呼叫fputc(c, fpOut); c==EOF ,这可能是未定义的行为,或者至少是写入\\0xff字节。

而且,您不会在while(argc--)循环内调用fclose ,因此您的文件(最后一个文件除外)绝不会关闭或刷新。

最后,您无需测试fopen的结果,而应测试它是否为非null(在这种情况下,输出一条错误消息,也许带有有关strerror(errno)perror )。

您应该已经找到了调试器(例如Linux上的gdb ),并可能借助了编译器警告(但是gcc-4.6 -Wall在示例中未发现任何错误)。

你可以决定输出文件名与输入文件名,也许

char outname[512];
for(i = 1; i < argc; i++) {
   fpIn = fopen(argv[i], "rb");
   if (!fpIn) { perror (argv[i]); exit(1); };
   memset (outname, 0, sizeof (outname));
   snprintf (outname, sizeof(outname)-1, "%s~%d.out", argv[i], i);
   fpOut= fopen(outname, "wb");
   if (!fpOut) { perror (outname); exit(1); };
   /// etc...
   fclose(fpIn);
   fclose(fpOut);
   fpIn = fpOut = NULL;
}

建议的更改(所有未经测试):

#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <stdio.h>

int 
main(int argc, char** argv) {

  FILE *fpIn, *fpOut;
  int i;
  char c;
  for(i = 1; i < argc; i++) {
    fpIn = fopen(argv[i], "rb");
    if (!fpIn) {
      perror ("Unable to open input file");
      continue;
     }
    fpOut= fopen("tmp.out", "wb");
    if (!fpOut) {
      perror ("Unable to open output file");
      fclose (fpIn);
      continue;
     }
     while ((c = fgetc (fpIn)) != EOF)) {
       if (isspace(c)) 
         c = '\n';
       fputc(c, fpOut );
     }
     fclose(fpIn);
     fclose(fpOut);
  }
  return 0;
}

暂无
暂无

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

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