3 - fgetc()函数

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:

  1. 参数stream是fgetc()函数要读取的流,类型为FILE*;stream可以是文件流或标准输入流;当是文件流时,stream就是fopen()函数的返回值;当是标准输入流时,stream就是stdin。

cstdio库描述如下:

stream
1. Pointer to a FILE object that identifies an input stream.

3 返回值

fgetc()函数的返回值类型为int型:

  1. 读取成功,返回从指定流stream中读取的字符(提升为int);
  2. 读取失败,返回EOF。

关于读取失败,分为两种情况:

  1. 读取遇到文件末尾,通过feof()函数检查;
  2. 读取过程发生错误,通过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()函数的工作原理类似,差异如下:

  1. fgetc()函数从指定流stream中读取字符; getchar()函数从标准输入流stdin中读取字符;
  2. 将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;
}

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

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值