fprintf有哪些用法
时间: 2024-05-02 10:17:30 浏览: 7
`fprintf` 函数是 C 语言中用于格式化输出数据到指定文件的函数,它的用法如下:
```c
int fprintf(FILE *stream, const char *format, ...);
```
其中,`stream` 参数是指向要写入数据的流对象的指针,一般是指定为 `stdout`(标准输出)或 `stderr`(标准错误输出);`format` 参数是一个格式化字符串,它包含了输出的格式和要输出的数据;`...` 表示可变参数,它可以是多个需要输出的数据。
以下是一些常见的用法:
1. 输出字符串到标准输出:
```c
fprintf(stdout, "Hello World!\n");
```
2. 输出整数到标准输出:
```c
int x = 123;
fprintf(stdout, "x = %d\n", x);
```
3. 输出浮点数到标准输出:
```c
double pi = 3.1415926;
fprintf(stdout, "pi = %.2f\n", pi);
```
4. 输出字符到标准输出:
```c
char ch = 'A';
fprintf(stdout, "ch = %c\n", ch);
```
5. 输出字符串到文件:
```c
FILE *fp = fopen("output.txt", "w");
fprintf(fp, "This is a test output.\n");
fclose(fp);
```
注意:使用 `fprintf` 函数时,需要确保输出的格式和参数数量匹配,否则会导致程序崩溃或输出错误。