使用文本文件二

关于以下代码的几个问题,我在之前的post中获得了帮助。

1)。 任何想法为什么在输出结束时,我得到一个随机的垃圾字符打印? 我正在释放文件等并检查EOF。

2)。 这个想法是它可以使用多个文件争论,所以我想创建新的文件名,增加,即out [i] .txt,是否可能在C?

代码本身接受一个文件,其中包含所有用空格分隔的单词,例如书籍,然后循环遍历,并用\ n替换每个空格以便它形成一个列表,请找到下面的代码:

#include  #include  #include  #include  /* * */ 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  #include  #include  #include  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; }