gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:35:37 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com