[英]When using fgetc() the assigned variable gives EOF
我正在將一個名為 strings.txt 的文件讀入 c 程序。 我在 Ubuntu 上運行它。 function 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.