1 函数原型
fgetc():从指定流stream中读取字符,函数原型如下:
int fgetc ( FILE * stream );
cstdio库描述如下:
Get character from stream
1. 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.
2. 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).
3. If a read error occurs, the function returns EOF and sets the error indicator for the stream (ferror).
2 参数
fgetc()函数只有一个参数stream:
- 参数stream是fgetc()函数要读取的流,类型为FILE*;stream可以是文件流或标准输入流;当是文件流时,stream就是fopen()函数的返回值;当是标准输入流时,stream就是stdin。
cstdio库描述如下:
stream
1. Pointer to a FILE object that identifies an input stream.
3 返回值
fgetc()函数的返回值类型为int型:
- 读取成功,返回从指定流stream中读取的字符(提升为int);
- 读取失败,返回EOF。
关于读取失败,分为两种情况:
- 读取遇到文件末尾,通过feof()函数检查;
- 读取过程发生错误,通过ferror()函数检查。
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 position indicator was at the end-of-file, the function returns EOF and sets the eof indicator (feof) of stream.
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 = NULL;
char ch = 0;
//
if ((fp = fopen("1.txt", "r")) == NULL)
{
perror("Failed to open file ");
exit(1);
}
//
while ((ch = fgetc(fp)) != EOF)
{
putchar(ch);
}
//
printf("\n");
//
fclose(fp);
//
return 0;
}
文件内容如下图所示:

代码运行结果如下图所示:

5.2 示例2
使用fgetc()函数读空标准输入流stdin并打印,示例代码如下所示:
int main()
{
//
char ch = 0;
//
while ((ch = fgetc(stdin)) != '\n')
{
putchar(ch);
}
//
printf("\n");
//
return 0;
}
代码运行结果如下图所示:


2451

被折叠的 条评论
为什么被折叠?



