[英]Entire file is not read in C (EOF occurs unexpectedly)
我正在嘗試打印大約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(EOF的數量)的值為3684,這意味着前220個字符之后的每個字符都將被讀取為EOF。 該程序即使填充了第一個220個字符也開始讀取FF
。
我認為代碼不錯,除了您應該將ch
更改為int
。
fgetc()
返回
int
” EOF
或錯誤” 因此,首先,您必須將ch
更改為int
,因為fgetc()
某些返回值可能不適合 char
。
現在,在第二種情況下,您無需針對EOF
檢查fgetc()
的返回值以檢測任何error。 您只是獲取返回值,然后嘗試將這些值存儲到數組中。 實際上,到達文件末尾時,不再需要讀取任何內容,並且在同一文件指針上進行的所有其他讀取操作都將返回錯誤。
這些值很可能是這些值。 在您的情況下220
之后有效 。
因此,對於您的問題中的陳述,
(EOF意外發生)
是錯的。 它發生得很好,您可以忽略它而遇到麻煩了 。
注意:
fgetc()
調用,實際上是丟棄第一個的結果,並且不經任何檢查就使用第二個的結果。 gets()
。 它遭受緩沖區溢出問題。 始終使用fgets()
代替。 以下代碼:
uses fgets() rather than the obsolete gets()
removed the newline from the user input
uses the proper size_t rather than int for indexing
is consistently indented
has modification to the printf statements to display size_t rather than int
compiles cleanly (which surprises me as payload is set but never used)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
int ch = ' ';
char file_name[25];
char payload[3904];
FILE *fp;
printf("Enter the name of file you wish to see\n");
fgets(file_name, sizeof(file_name), stdin);
// remove trailing newline
char *newline = strstr(file_name, "\n" );
if (newline ) *newline = '\0';
fp = fopen(file_name, "r"); // read mode
if (fp == NULL)
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
// implied else, fopen successful
printf("The contents of %s file are :\n", file_name);
size_t gin = 0;
while ( ((ch = fgetc(fp)!=EOF)) && (sizeof(payload) > gin) )
{
printf("%ld) %x \n",gin, ch);
payload[gin++] = ch;
}
printf("Also, value of gin is %ld --->", gin);
getchar();
//...rest of the code
return(0);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.