简体   繁体   中英

When using fgetc() the assigned variable gives EOF

I am reading a file called strings.txt into the c program. I am running this on Ubuntu. The function fgets() works but fgetc() always returns EOF instead of the char. What am I doing wrong?

I know that fgetc returns EOF if that point is reached or if there is an error somewhere. But where is the error?

The strings.txt file is included as the second file below.

#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

You can call ferror() to determine if an error occurred.

You should be able to call perror() with the value you got from ferror() to get a human-readable error message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM