C,getc / fgetc - 终止为null

时间:2016-01-18 16:40:25

标签: c file fgetc null-terminated

我正在编写用C计算单词的程序,我知道我可以用fscanf简单地完成这个。但我正在使用getc。

我的文件是这样的:

  

一二三四五。

我在while循环中读取字符,而且当我到达终端null时,断点。

{1}}或c = fgetc(input);会在One_之后和之后设置c = getc(input);等等吗?

1 个答案:

答案 0 :(得分:1)

getc()之类的函数的返回值为EOF为-1时,您已到达file.try的末尾,此代码用于计算单词:

#include <stdio.h>

int WordCount(FILE *file);

int main(void)
{
    FILE *file;
    if(fopen_s(&file,"file.txt","r")) {
        return 1;
    }
    int n = WordCount(file);
    printf("number of words is %d\n", n);
    fclose(file);
    return 0;
}

int WordCount(FILE *file)
{
    bool init = 0;
    int count = 0, c;
    while((c = getc(file)) != EOF)
    {
        if(c != ' ' && c != '\n' && c != '\t') {
            init = 1;
        }
        else {
            if(init) {
                count++;
                init = 0;
            }
        }
    }
    if(init)
        return (count + 1);
    else
        return count;
}