我有以下C程序:
#include <stdio.h>
int main()
{
FILE *f1, *f2, *f3;
int number, i;
printf("Contents of data file\n\n");
f1=fopen("DATA", "w");
for(i=1; i<=10; i++)
{
scanf("%d", &number);
if(number==-1)
{
break;
}
putw(number,f1);
}
fclose(f1);
f1=fopen("DATA","r");
f2=fopen("ODD","w");
f3=fopen("EVEN","w");
while((number=getw(f1)) != EOF)
{
if(number%2==0)
{
putw(number,f3);
}
else
{
putw(number,f2);
}
}
fclose(f1);
fclose(f2);
fclose(f3);
f2=fopen("ODD","r");
f2=fopen("EVEN","r");
printf("Contents on ODD file:");
while((number=getw(f2)) != EOF)
{
printf("%4d", number);
}
printf("Contents on EVEN file:");
while((number=getw(f3)) != EOF)
{
printf("%4d", number);
}
fclose(f2);
fclose(f3);
return 0;
}
此程序无限输入 FILE f1 。按 -1 后应终止。但它不!我按了CTRL+D
。但什么都没发生。我不明白问题出在哪里。
答案 0 :(得分:4)
(number=getw(f1))
而不是
(number==getw(f1))
你的程序将以这种方式永远循环你的第一个while
子句。
您应该使用"wb"
和"rb"
而不是"w"
和"r"
打开文件,因为putw()
和getw()
都期望以二进制模式打开的文件。
答案 1 :(得分:0)
我尝试了相同的代码并进行了一些小的更正,如果有用的话,它可以正常运行:
int main()
{
FILE *f1, *f2, *f3;
int number, i;
printf("Contents of data file\n\n");
f1=fopen("DATA", "w");
for(i=1; i<=10; i++)
{
scanf("%d", &number);
if(number==-1)
{
break;
}
putw(number,f1);
}
fclose(f1);
f1=fopen("DATA","r");
f2=fopen("ODD","w");
f3=fopen("EVEN","w");
while((number=getw(f1)) != EOF)
{
if(number%2==0)
{
putw(number,f3);
}
else
{
putw(number,f2);
}
}
fclose(f1);
fclose(f2);
fclose(f3);
f2=fopen("ODD","r");
f3=fopen("EVEN","r");
printf("Contents on ODD file:");
while((number=getw(f2)) != EOF)
{
printf("%4d", number);
}
printf("Contents on EVEN file:");
while((number=getw(f3)) != EOF)
{
printf("%4d", number);
}
fclose(f2);
fclose(f3);
return 0;
}
答案 2 :(得分:0)
你写过
f2=fopen("ODD","r");
f2=fopen("EVEN","r");
但应该写
f2=fopen("ODD","r");
f3=fopen("EVEN","r");
无论如何,希娜已经纠正了这个......应该用f3指出偶数流