如果我们的main函数不想修改printf的写法呢
时间: 2023-10-01 16:03:20 浏览: 47
如果你不想修改 `main` 函数中 `printf` 的写法,你可以考虑定义一个新的函数,例如 `my_printf`,来代替标准库中的 `printf` 函数。你可以在 `my_printf` 函数中调用 `redirect_printf` 函数来实现输出重定向的功能。这样,你就可以在 `main` 函数中继续使用标准库中的 `printf` 函数,而不需要对其进行修改。
下面是一个示例代码:
```c
#include <stdio.h>
#include <stdarg.h>
void redirect_printf(const char* filename, const char* format, ...) {
// 打开指定文件
FILE* file = fopen(filename, "a");
if (file == NULL) {
fprintf(stderr, "Failed to open file %s\n", filename);
return;
}
// 使用 va_list 处理可变参数列表
va_list args;
va_start(args, format);
vfprintf(file, format, args);
va_end(args);
// 关闭文件
fclose(file);
}
int my_printf(const char* format, ...) {
redirect_printf("output.txt", format, ...); // 调用 redirect_printf 函数输出到文件中
// 调用标准库的 printf 函数输出到控制台
va_list args;
va_start(args, format);
int ret = vprintf(format, args);
va_end(args);
return ret;
}
int main() {
my_printf("Hello, %s!\n", "world");
printf("This is a test.\n");
my_printf("%d + %d = %d\n", 1, 2, 3);
return 0;
}
```
在这个示例代码中,我们定义了一个新的函数 `my_printf`,该函数调用了 `redirect_printf` 函数来将输出重定向到指定的文件中,并且还调用了标准库中的 `vprintf` 函数来将输出输出到控制台。在 `main` 函数中,我们可以继续使用标准库中的 `printf` 函数来输出到控制台,也可以使用 `my_printf` 函数来将输出重定向到指定的文件中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)