При использовании fgetc () назначенная переменная дает EOF - PullRequest
0 голосов
/ 18 октября 2019

Я читаю файл с именем 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);
...
}

strings.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

1 Ответ

1 голос
/ 18 октября 2019

Вы можете позвонить ferror(), чтобы определить, произошла ли ошибка.

Вы должны иметь возможность вызвать perror() со значением, которое вы получили от ferror(), чтобы получить читаемое человеком сообщение об ошибке.

...