fprintf函数的用法
时间: 2023-09-26 22:05:49 浏览: 23
fprintf函数是C语言标准库中的一个输出函数,主要用于将格式化的数据输出到文件或标准输出设备(屏幕)。其语法如下:
```c
int fprintf(FILE *stream, const char *format, ...);
```
其中,stream为输出流,可以是文件指针或标准输出设备(stdout),format为格式化输出字符串,...表示可变参数列表,根据format中的占位符进行格式化输出。
示例:
```c
#include <stdio.h>
int main()
{
int a = 10;
double b = 3.14159;
char c = 'A';
char str[] = "Hello, World!";
// 输出到标准输出设备
fprintf(stdout, "a = %d, b = %.2f, c = %c, str = %s\n", a, b, c, str);
// 输出到文件
FILE *fp = fopen("output.txt", "w");
fprintf(fp, "a = %d, b = %.2f, c = %c, str = %s\n", a, b, c, str);
fclose(fp);
return 0;
}
```
输出结果:
```
a = 10, b = 3.14, c = A, str = Hello, World!
```
注意,使用fprintf函数输出到文件时,需要先打开文件并获得文件指针,输出完成后还需要关闭文件。