读书人

文件的操作有误如何会有那么多的填充

发布时间: 2012-11-05 09:35:12 作者: rapoo

文件的操作有误,怎么会有那么多的填充字
代码如下
#include <stdio.h>
#include <stdlib.h>

void main ()
{
FILE *fp1, *input, *output;
char ch;

if((fp1 = fopen("wang.txt", "wt")) == NULL)
{
printf("can not open this file\n");
exit(0);
}

for (; (ch = getchar())!= '@';)
fputc (ch, fp1);
fclose (fp1);

if((input = fopen("wang.txt", "r")) == NULL)
{
printf("can not open source file\n");
exit (0);
}

if ((output = fopen("yun.txt","w")) == NULL)
{
printf("can not create a new file\n");
exit (0);
}

for(; (!feof(input));)
fputc(fgetc(input),output);

fclose (input);


for(; (ch = fgetc(output)) != '4';)
putchar(ch);

fclose (output);


}

输入12345678@回车之后,显示一大串的的填充字,求解释

[解决办法]
没太明白你的目的,不过从目前的操作,至少有些地方需要改进:
语句

C/C++ code
if ((output = fopen("yun.txt", "w")) == NULL)
[解决办法]

注意原因:
1,用fget函数处理了以写方式打开的文件;
2,循环退出条件应该加上判断文件是否结束,否则如果文件中没有出现4,就会成死循环了
C/C++ code
#include <stdio.h>#include <stdlib.h>void main (){    FILE *fp1, *input, *output;    char ch;    if((fp1 = fopen("wang.txt", "wt")) == NULL)    {        printf("can not open this file\n");        exit(0);    }    for (; (ch = getchar())!= '@';)        fputc (ch, fp1);    fclose (fp1);    if((input = fopen("wang.txt", "r")) == NULL)    {        printf("can not open source file\n");        exit (0);    }    if ((output = fopen("yun.txt","w")) == NULL) //可以用写读方式打开,但是在写之前要加上fseek(output,0,0);    {        printf("can not create a new file\n");        exit (0);    }    for(; (!feof(input));)        //这种方式是对的,可以用feof来判断是文件是否结束,不过这种写法不是很好看        fputc(fgetc(input),output);    //while((ch=fgetc(input))!= EOF)          //这种写法更好看一些        //fputc(ch, output);    fclose (input);    fclose( output );    if ((output = fopen("yun.txt","r")) == NULL)         //应该用读的方式打开文件,不能对写文件加fget操作    {        printf("can not create a new file\n");        exit (0);    }//    for(; (ch = fgetc(output)) != '4';)                //对写文件加fget操作时错误的//        putchar(ch);    //fseek(output,0,0);        //如果是读写方式打开的话,要调整写指针到文件头部    while( ch = fgetc(output), ch!=4 && ch!=EOF )        //最好判断一下文件是否结束了,否则如果output文件中没有4的话,会死循环         putchar(ch);    fclose (output);}
[解决办法]
不要使用
while (条件)
更不要使用
while (组合条件)
要使用
while (1) {
if (条件1) break;
//...
if (条件2) continue;
//...
if (条件3) return;
//...
}
因为前两种写法在语言表达意思的层面上有二义性,只有第三种才忠实反映了程序流的实际情况。
典型如:
下面两段的语义都是当文件未结束时读字符
whlie (!feof(f)) {
a=fgetc(f);
//...
b=fgetc(f);//可能此时已经feof了!
//...
}
而这样写就没有问题:
whlie (1) {
a=fgetc(f);
if (feof(f)) break;
//...
b=fgetc(f);
if (feof(f)) break;
//...
}
类似的例子还可以举很多。

[解决办法]
探讨

不要使用
while (条件)
更不要使用
while (组合条件)
要使用
while (1) {
if (条件1) break;
//...
if (条件2) continue;
//...
if (条件3) return;
//...
}
因为前两种写法在语言表达意思的层面上有二义性,只有第三种才忠实反映了程序流的实际情况。


典型如:
下面两段的语……

读书人网 >C语言

热点推荐