5 - fputc()函数

1 函数原型

fputc():将字符写入指定流stream,函数原型如下:

int fputc ( int character, FILE * stream );

cstdio库描述如下:

Write character to stream
1. Writes a character to the stream and advances the position indicator.
2. The character is written at the position indicated by the internal position indicator of the stream, which is then automatically advanced by one.

2 参数

fputc()函数有两个参数character和stream:

  1. 参数character是写入指定流stream的字符,类型为int;
  2. 参数stream是fputc()函数要写入的流,类型为FILE*;stream可以是文件流或标准输出流;当是文件流时,stream就是fopen()函数的返回值;当是标准输出流时,stream就是stdout和stderr。

cstdio库描述如下:

character
1. The int promotion of the character to be written.
2. The value is internally converted to an unsigned char when written.

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

3 返回值

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

  1. 写入成功,返回写入指定流stream的字符;
  2. 写入失败,返回EOF。

cstdio库描述如下:

1. On success, the character written is returned.
2. If a writing error occurs, EOF is returned and the error indicator (ferror) is set.

4 比较

fputc()函数和putchar()函数的工作原理类似,差异如下:

  1. fputc()函数将字符写入指定流stream;putchar()函数将字符写入标准输出流stdout;
  2. 将fputc()函数的参数stream指定为stdout,则fputc()函数的功能和putchar()函数的功能完全相同。

5 示例

5.1 示例1

以ASCII码值和字符常量的形式输出单个字符,示例代码如下所示:

int main()
{
   //
   FILE* fp = NULL;
   //
   if ((fp = fopen("1.txt", "w")) == NULL)
   {
      perror("Failed to open file ");
      exit(1);
   }
   //
   char str1[] = { 97, 98, 99, 100, 101, 102 };
   char str2[] = { 'a', 'b', 'c', 'e', 'e', 'f' };
   //
   int i = 0;
   //
   for (i = 0; i < 6; i++)
   {
      fputc(str1[i], fp);
   }
   //
   fputc('\n', fp);
   //
   for (i = 0; i < 6; i++)
   {
      fputc(str2[i], fp);
   }
   //
   fclose(fp);
   //
   return 0;
}

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

在这里插入图片描述

5.2 示例2

从键盘读取字符串"hello world"并打印,示例代码如下所示:

int main()
{
   //
   char ch = 0;
   //
   while ((ch = getchar()) != '\n')
   {
      fputc(ch, stdout);
   }
   //
   printf("\n");
   //
   return 0;
}

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

在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值