c - 当使用 fgetc() 时,分配的变量给出 EOF

标签 c text fgetc

我正在将一个名为 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

最佳答案

您可以调用ferror()以确定是否发生错误。

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

关于c - 当使用 fgetc() 时,分配的变量给出 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58456023/

相关文章:

c - linux fork通信

c - 如果我们只有一个 MQ,则同步 IBM MQ : need or not,

javascript - 动态更改跨度的文本格式

text - 为什么文本在游戏引擎中看起来如此糟糕?

c - 二维数组struct — malloc()和free()

c - int 转位串函数来处理负数

python - 删除两个句号之间的数字

c - 如何将文件中的单词保存到数组中?

我可以在二进制文件中使用 fgetc() 或 fputc() 吗?