【发布时间】:2015-07-09 06:40:16
【问题描述】:
我正在尝试打印大约 4000 个字符的文件内容。 不知何故,程序只记录前 220 个字符并终止。
int main(void)
{
char ch = ' ', file_name[25], payload[3904];
FILE *fp;
printf("Enter the name of file you wish to see\n");
gets(file_name);
fp = fopen(file_name, "r"); // read mode
if (fp == NULL)
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
printf("The contents of %s file are :\n", file_name);
int gin = 0;
while ((ch = fgetc(fp)!=EOF))
{
printf("%d) %x \n",gin, ch);
payload[gin++] = ch;
}
printf("Also, value of gin is %d --->", gin);
getchar();
//...rest of the code
}
这里gin的值为220。
为了检查,我修改了while() 条件以运行文件中的确切字符数:
{
//...
while (gin<3904)
{
if ((ch = fgetc(fp)) == EOF) res++;//ADDED THIS TO COUNT NUMBER OF EOF's
printf("%d) %x \n",gin, ch);
payload[gin++] = ch;
//printf(" %x \n", payload[(gin - 1)]);
if (gin % 100 == 0)
{
printf("Also, value of res is %d --->", res); getchar();
getchar();
}
}
//...rest of the code
}
gin 的值达到 3904,res(no. of EOF's) 的值是 3684,这意味着第一个 220 之后的每个字符都被读取为 EOF。程序在第一个 220 个字符之后开始读取 FF,即使它已被填充。
【问题讨论】:
-
您想将
c设为int。看看fgetc()返回什么类型。 -
gets()很危险...改用fgets()。 -
@sourav 它说:“fgets 的字符太少”
-
哦,来吧,请查看手册页.....
-
您调用
fgetc两次,结果第一个被丢弃。结果是第二个字符没有被计算或存储。