1 函数原型
fputc():将字符character写入指定流stream,函数原型如下:
int fputc(int character, FILE *stream);
cstdio库描述如下:
1. Write character to stream.
2. Writes a character to the stream and advances the position indicator.
3. 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:
- 参数character是写入指定流stream的字符,类型为int;
- 参数stream是一个指向FILE类型结构的指针;stream指定了fputc()函数要写入的流,可以是文件流,也可以是标准输出流;当是文件流时,stream就是fopen()函数的返回值;当是标准输出流时,stream就是stdout。
cstdio库描述如下:
参数1:character
1. The int promotion of the character to be written.
2. The value is internally converted to an unsigned char when written.
参数2:stream
1. Pointer to a FILE object that identifies an output stream.
3 返回值
fputc()函数的返回值类型为int型:
- 输出成功,返回写入指定流stream的字符(由unsigned char转换为int);
- 输出失败,返回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()函数的工作原理类似,差异如下:
- fputc()函数将字符写入指定流stream;
- putchar()函数将字符写入标准输出流stdout;
- 将fputc()函数的参数stream指定为stdout,则fputc()函数的功能和putchar()函数的功能完全相同。
5 示例
5.1 示例1
以ASCII码值和字符常量的形式输出单个字符,代码如下所示:
int main()
{
FILE* fp;
if ((fp = fopen("1.txt", "w")) == NULL)
{
printf("Failed to open file\n");
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' && ch != EOF)
{
fputc(ch, stdout);
}
//
printf("\n");
//
return 0;
}
代码运行结果如下图所示: