本文介绍了Ç - 与工作的fopen和fclose的fputc等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这有code终于在我的命令行一个参数工作,即一个文件为它一起工作,虽然我设计了$ C​​ $ c。与它的无限数量的工作理念的文件。它所做的是利用含有空格隔开的单词的文本文件的一些X数字,并用替换空间\\ n 从而创造一个单词列表。虽然,它成功完成了第一个参数,它只是忽略了第二位。

另一个小问题似乎还打印出在年底一些垃圾信件,A Y带两个点它上面;我认为一些EOF符号,但我似乎无法阻止这种情况发生!

  INT主(INT ARGC,字符** argv的){
    FILE * fpIn,* fpOut;
    INT I,J;
    J = 1;
    焦炭℃;
    焦炭的myString [256];    的printf(%D的argc);
    的printf(\\ n);
    的printf(以下参数传递给main());
                对于(i = 1; I< ARGC,我++)的printf(%S的argv [I]);
    的printf(\\ n);    而(argc--){
        对于(i = 1; I< ARGC,我++){
            fpIn = FOPEN(的argv [J],RB);
            的snprintf(MyString的,256,%S〜[%D]。的argv [J],I);
            fpOut = FOPEN(MyString的,WB);
            而(C!= EOF){
                C =龟etc(fpIn);
                如果(isspace为(c))的
                    C ='\\ n';
                的fputc(C,fpOut);
            }
            J ++;
        }
    }
    返回0;
}


解决方案

的getchar() GETC()龟etc()函数(或宏)返回一个 INT ,而不是字符

您必须使用:

  INT℃;而((C =龟etc(fpIn))!= EOF)
{
    如果(isspace为(c))的
        C ='\\ n';
    的fputc(C,fpOut);
}

想想吧;该功能必须能够返回任何有效的字符的EOF(这是任何有效截然不同字符价值,因此,根据定义,返回值不能是字符 ...

如果您使用会发生什么字符


  • 您原来的code没有初始化 C 之前对其进行测试(因此该循环可能会提早结束)。

  • 您$​​ C $ C没有测试 C 阅读EOF后立即(所以它可能会打印垃圾字符,经常Y,拉丁小写字母Y带分音符,U + 00FF)。

  • 如果你的字符类型是无符号的,你永远不会看到EOF。

  • 如果你的字符类型有符号,一些有效的字符(经常再次Y))将作为PTED EOF misinter $ P $。


The problem there is the double loop you have running:

int i, j;
j = 1;

while (argc--)
{
    for (i = 1; i < argc; i++)
    {
        fpIn = fopen(argv[j], "rb");
        ...process fpIn...
        j++;
    }
}

Let us suppose you invoke the command with two file names; then argc == 3.

After the first time past the while loop, argc == 2. You then do a for loop with i taking the value 1; you open argv[1] (because j == 1). You process that file; then increment j to 2, before also incrementing i, also to 2. The second time around the for loop, i == 2 as does argc, so the for loop terminates. The while loop decrements argc again to 1, but tests that 2 != 0. However, the for loop sets i = 1 and then terminates because i == argc. The while loop decrements argc to 1, and repeats.

You can use a while loop or a for loop, but you don't need both.

So, either:

for (i = i; i < argc; i++)
{
    ...process argv[i]...
}

Or:

while (--argc > 0)
{
    ...process *++argv...
}

I'd use the for loop.

这篇关于Ç - 与工作的fopen和fclose的fputc等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 17:41
查看更多