当前位置: C语言 -- 标准库 -- <stdio.h> -- fgetc

fgetc函数


概要:
#include <stdio.h>
int fgetc(FILE *stream);

描述:

该函数从参数stream指向的输入流中读取一个字符,具体步骤:如果参数stream指向输入流未设置文件末尾指示符(end-of-file indicator),并且存在下一个字符,函数将读取该字符,同时将字符从unsigned char类型转换为int类型;如果定义了文件位置指示符,并前进文件位置指示符。

:根据ISO/IEC 9899:2018标准第7.21.3 Files节,文件打开时,如果文件支持定位请求,与流相关联的文件位置指示符指示位置在文件开始处(即0号字符。);除非使用a模式打开文件,这种情况下,文件位置指示符指示位置是文件开始处,还是文件末尾处将由实现定义。


参数:
FILE *stream

FILE类型指针,指向输入流。


返回值:

如果设置了流的文件末尾指示符,或者如果流处于文件末尾位置,将设置流的文件末尾指示符,函数返回EOF;否则函数返回读取的字符。如果发生读取错误,将给流设置错误指示符(error indicator),并返回EOF


范例:
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
/*函数fgetc范例*/

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int ch;
    int count = 0;  //统计元音字母数。
    const char vowel[5] = "aeiou";
    FILE *pFile;

    /*打开文件。*/
    pFile = fopen("gch.txt", "r");
    if(!pFile)
    {
        perror("Error");
        exit(EXIT_FAILURE);
    }
    
    /*遍历文件。*/
    while((ch=fgetc(pFile)) != EOF)
    {
        for(int i=0; i<5; ++i)
        {
            if(tolower(ch)==vowel[i])
                ++count;
        }
    }

    /*关闭文件。*/
    fclose(pFile);

    printf("vowel: %d\n", count);

    return 0;
}


结果:

假设gch.txt文件内容为:

The man who has made up his mind to win will never say "impossible". -Napoleon

将输出:

vowel: 23


相关内容:
fgets 从输入流读取字符串的函数。
getc 从输入流读取字符的函数。
getchar 从标准输入流读取字符的函数。
ungetc 将字符推回输入流的函数。