1 函数原型
fgetc():从指定流stream中读取一个字符,函数原型如下:
int fgetc(FILE *stream)
cstdio库描述如下:
1. Get character from stream.
2. Returns the character currently pointed by the internal file position indicator of the specified stream. The internal file position indicator is then advanced to the next character.
3. If the stream is at the end-of-file when called, the function returns EOF and sets the end-of-file indicator for the stream (feof).
4. If a read error occurs, the function returns EOF and sets the error indicator for the stream (ferror).
2 参数
fgetc()函数只有一个参数stream:
- 参数stream是一个指向FILE类型结构的指针;stream指定了fgetc()函数要读取的流,可以是文件流,也可以是标准输入流;当是文件流时,stream等于fopen()函数的返回值;当是标准输入流时,stream等于stdin。
cstdio库描述如下:
1. Pointer to a FILE object that identifies an input stream.
3 返回值
fgetc()函数的返回值类型为int型:
- 读取成功,以无符号char强制转换为int的形式(整型提升)返回读取的字符;
- 读取失败,返回EOF。
关于读取失败,分为两种情况:
- 读取遇到文件末尾(疑问:从stdin中读取字符怎么会遇到文件末尾);
- 读取过程发生错误(疑问:从stdin中读取字符会发生什么样的错误)。
cstdio库描述如下:
1. On success, the character read is returned (promoted to an int value).
2. The return type is int to accommodate for the special value EOF, which indicates faliure.
3. If the standand input was at the end-of-file, the function returns EOF and sets the eof indicator (feof) of stdin.
4. If some other reading error happens, the function also returns EOF, but sets its error indicator (ferror) instead.
4 比较
fgetc()函数和getchar()函数的工作原理类似,差异如下:
- fgetc()函数从指定流stream中读取字符;
- getchar()函数从标准输入流stdin中读取字符;
- 将fgetc()函数的参数stream指定为stdin,则fgetc()函数的功能和getchar()函数的功能完全相同。
5 示例
5.1 示例1
使用fgetc()函数从文件读取字符并打印,代码如下所示:
int main()
{
FILE* fp;
char ch;
if ((fp = fopen("1.txt", "r")) == NULL)
{
printf("Failed to open file.\n");
exit(1);
}
while ((ch = fgetc(fp)) != EOF)
{
putchar(ch);
}
printf("\n");
fclose(fp);
return 0;
}
文件包含内容如下图所示:
代码运行结果如下图所示:
5.2 示例2
使用fgetc()函数从标准输入流stdin读取字符串"hello world"并打印,代码如下所示:
int main()
{
//
char ch = 0;
while ((ch = fgetc(stdin)) != '\n' && ch != EOF)
{
putchar(ch);
}
//
printf("\n");
//
return 0;
}
代码运行结果如下图所示: