我正在将名为string.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