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

getc函数


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

描述:

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

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

该函数等价于fgetc函数,唯一的区别在于:如果实现将getc定义为函数式宏,可能会对参数stream多次评估,因此参数stream应为不带副作用的表达式;而fgetc只能以函数形式实现。


参数:
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 
40 
41 
42 
43 
/*函数getc范例*/

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

int main(void)
{
    int ch;
    int vowel = 0;  //统计元音字母数。
    int letter = 0;  //统计字母数。
    const char str[] = {'a', 'e', 'i', 'o', 'u'};
    FILE *pFile;

    /*打开文件。*/
    pFile = fopen("gch.txt", "r");
    if(!pFile)
    {
        perror("Error");
        exit(EXIT_FAILURE);
    }
    
    /*遍历文件。*/
    while((ch=getc(pFile)) != EOF)
    {
        if(isalpha(ch))
            ++letter;

        for(int i=0; i<sizeof(str)/sizeof(str[0]); ++i)
        {
            if(tolower(ch)==str[i])
                ++vowel;
        }
    }

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

    printf("consonant: %d\n", (letter-vowel));

    return 0;
}


结果:

假设gch.txt文件内容为:

In war the strong makes slaves of the weak, and in peace the rich makes slaves of poor. -Wilde

将输出:

consonant: 45


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