整个文件未在C中读取(意外发生EOF)

时间:2015-07-09 06:40:17

标签: c file-io

我正在尝试打印大约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&#39; s的值)是3684,这意味着在第一个220之后的每个字符都被读作EOF。该程序在前220个字符后开始读取FF,即使它已被填充。

2 个答案:

答案 0 :(得分:4)

我认为代码很好,除了您应该将ch更改为int

fgetc()返回

  • 如果成功,&#34;将字符读作无符号字符转换为int&#34;
  • 如果失败,&#34; EOF在文件末尾或错误&#34;

首先,您必须将ch更改为int,因为来自fgetc()的某些返回值可能不适合 a char }。

现在,在第二种情况下,您不会检查fgetc()EOF的返回值以检测任何错误。您只需获取返回值并尝试将这些值存储到数组中。实际上,当到达文件末尾时,没有什么可以读取的,并且对同一文件指针的所有进一步读取将返回错误。

这些价​​值最有可能。在您的情况下220 有效之后

那么,对于你问题中的陈述,

  

(意外发生EOF)

错了。它发生得很好,你忽略了它并且遇到了,麻烦

注意:

  1. 在您的第一个代码段中,您正在进行两次连续的fgetc()次呼叫,实质上是丢弃第一次呼叫的结果,而使用第二次呼叫则没有任何检查。
  2. 永远不要使用gets()。它遇到缓冲区溢出问题。请始终使用fgets()

答案 1 :(得分:0)

以下代码:

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);
}