vprintf,+vfprintf和+vsprintf
时间: 2024-01-22 15:16:38 浏览: 27
vprintf函数是一个可变参数的输出函数,它将格式化的数据输出到标准输出设备。vfprintf函数是一个可变参数的输出函数,它将格式化的数据输出到指定的文件流中。vsprintf函数是一个可变参数的输出函数,它将格式化的数据输出到一个字符串中。
下面是对vprintf、vfprintf和vsprintf函数的介绍和演示:
1. vprintf函数的使用示例:
```c
#include <stdio.h>
#include <stdarg.h>
void my_printf(const char* format, ...)
{
va_list args;
va_start(args, format);
vprintf(format, args);
va_end(args);
}
int main()
{
my_printf("Hello, %s! The answer is %d.\n", "world", 42);
return 0;
}
```
输出结果:
```
Hello, world! The answer is 42.
```
2. vfprintf函数的使用示例:
```c
#include <stdio.h>
#include <stdarg.h>
void my_fprintf(FILE* stream, const char* format, ...)
{
va_list args;
va_start(args, format);
vfprintf(stream, format, args);
va_end(args);
}
int main()
{
FILE* file = fopen("output.txt", "w");
my_fprintf(file, "Hello, %s! The answer is %d.\n", "world", 42);
fclose(file);
return 0;
}
```
输出结果:在当前目录下生成一个名为output.txt的文件,内容为:
```
Hello, world! The answer is 42.
```
3. vsprintf函数的使用示例:
```c
#include <stdio.h>
#include <stdarg.h>
void my_sprintf(char* str, const char* format, ...)
{
va_list args;
va_start(args, format);
vsprintf(str, format, args);
va_end(args);
}
int main()
{
char buffer[100];
my_sprintf(buffer, "Hello, %s! The answer is %d.\n", "world", 42);
printf("%s", buffer);
return 0;
}
```
输出结果:
```
Hello, world! The answer is 42.
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)