【问题标题】:When using fgetc() the assigned variable gives EOF使用 fgetc() 时,分配的变量给出 EOF
【发布时间】:2019-10-18 18:03:17
【问题描述】:

我正在将一个名为 strings.txt 的文件读入 c 程序。我在 Ubuntu 上运行它。函数 fgets() 有效,但 fgetc() 总是返回 EOF 而不是 char。我做错了什么?

我知道如果达到该点或某处出现错误, fgetc 将返回 EOF。但是错误在哪里?

strings.txt 文件包含在下面的第二个文件中。

#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define MAX 1024

void *num_substring(void *hold);

int total = 0;
int n1,n2;
char *s1,*s2;
FILE *fp;
int at;

int readf(FILE *fp)
{
    char c;
    int words = 1;

    fp=fopen("strings.txt", "r");
    if(fp==NULL){
        printf("ERROR: can't open string.txt!\n");
        return 0;
    }
    else
    {
        s1=(char *)malloc(sizeof(char)*MAX);
        if(s1==NULL){
            printf("ERROR: Out of memory!\n");
            return -1;
        }
        s2=(char *)malloc(sizeof(char)*MAX);
        if(s2==NULL){
            printf("ERROR: Out of memory\n");
            return -1;
        }
        /*read s1 s2 from the file*/
        s1=fgets(s1, MAX, fp);
        s2=fgets(s2, MAX, fp);
        n1=strlen(s1);  /*length of s1*/
        n2=strlen(s2)-1; /*length of s2*/

        //error happens here and the while is never run
        c = fgetc(fp);
        while (c == EOF)
        {
            printf("c != EOF\n");
            if (c == '\n' || c == ' ')
            {
                words++;
                printf("word in loop count = %d\n", words);
            }

            c = fgetc(fp);
        }
...
}

int main(int argc, char *argv[])
{
    int count;

    count = readf(fp);
...
}

字符串.txt

This is an apple. That is a pear. That is an orange. That is a kiwi fruit. This is an avocado. There is a peach on the tree. This is a banana. That is a berry. That is cherry. That is a haw. This is a lemon. There is a hickory on the tree. 
is

【问题讨论】:

  • fgetc() 返回int,而不是char
  • 我看了这里:ecomputernotes.com/c-program/…,作者有char c; c = fgetc([file])
  • 确实应该是int,作者在这里用错了类型。这个想法是fgetc() 可能返回EOF,这远远超出了char 的范围。使用更规范的参考来验证用法,例如cplusplus.com/reference/cstdio/fgetc
  • 看起来你的程序调用fgets 两次,读取两行,然后调用fgetc 从文件中读取任何剩余的字符。但是由于您的文本文件仅包含两行,因此没有其他内容可阅读。所以fgetc 的 EOF 返回似乎是正确的,除非我遗漏了什么。
  • @Jinzu s2=(char *)malloc(sizeof(char)*MAX); --> s2=malloc(MAX); as sizeof (char) == 1 always 而从不 cast malloc in C

标签: c text fgetc


【解决方案1】:

您可以致电ferror() 确定是否发生错误。

您应该能够使用从ferror() 获得的值调用perror() 以获得人类可读的错误消息。

【讨论】:

  • perror() 给我成功,它没有错误
猜你喜欢
  • 1970-01-01
  • 2012-06-18
  • 2013-08-16
  • 2019-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多