使用文本文件二

时间:2011-12-27 20:39:35

标签: c io fopen fclose

关于下面代码的几个问题,我在上一篇文章中获得了帮助。

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;
}

2 个答案:

答案 0 :(得分:2)

当您到达文件末尾时,您不会break循环。所以你用fputc(c, fpOut);调用c==EOF这可能是一个未定义的行为,或者至少写了一个\0xff字节。

并且您不会在fclose循环中调用while(argc--),因此您的文件(除了最后一个)大多数都不会被关闭或刷新。

最后,您不测试fopen的结果,您应该测试它是否为空(并打印错误消息,可能包含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;
}

答案 1 :(得分:1)

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

#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;
}