C 语言输出重定向与文件保存92


在 C 语言中,程序输出通常会显示在控制台上。然而,有时我们需要将输出重定向到文件中,以便进行持久化存储或进一步处理。本文将介绍 C 语言中输出保存的几种方法。## 重定向到文件


printf() 函数
我们可以使用 `printf()` 函数将输出重定向到文件。`printf()` 函数的签名如下:
```c
int printf(const char *format, ...);
```
其中,第一个参数 `format` 指定输出格式,后续参数是将要输出的值。为了将输出重定向到文件,我们需要使用 `freopen()` 函数打开一个文件并将其关联到标准输出流 `stdout`。语法如下:
```c
FILE *freopen(const char *path, const char *mode, FILE *stream);
```
其中:
* `path`:要打开的文件路径
* `mode`:打开模式(例如 "w" 表示写入模式,"a" 表示追加模式)
* `stream`:要关联的流(例如 `stdout`)
重定向的示例代码如下:
```c
#include
int main() {
FILE *fp = freopen("", "w", stdout);
if (fp == NULL) {
perror("freopen() failed");
return EXIT_FAILURE;
}
printf("Hello, world!");
fclose(fp);
return EXIT_SUCCESS;
}
```


fprintf() 函数
`fprintf()` 函数与 `printf()` 函数类似,但它允许我们直接将输出写入指定的流。`fprintf()` 的签名如下:
```c
int fprintf(FILE *stream, const char *format, ...);
```
其中:
* `stream`:要写入的流(例如 `stdout`)
* `format`:输出格式
* 后续参数:要输出的值
使用 `fprintf()` 进行重定向的示例代码如下:
```c
#include
int main() {
FILE *fp = fopen("", "w");
if (fp == NULL) {
perror("fopen() failed");
return EXIT_FAILURE;
}
fprintf(fp, "Hello, world!");
fclose(fp);
return EXIT_SUCCESS;
}
```
## 控制台输出与文件输出同时进行
如果我们希望既在控制台上显示输出,又在文件中保存输出,我们可以使用 `tee` 命令。`tee` 命令将标准输入的副本写入指定的文件。示例代码如下:
```
echo "Hello, world!" | tee
```
## 总结
C 语言提供了多种方法来保存输出。我们可以使用 `freopen()` 函数将 `stdout` 重定向到文件,或者直接使用 `fprintf()` 函数将输出写入文件。如果需要同时在控制台上显示输出和保存到文件,我们可以使用 `tee` 命令。

2024-11-09


上一篇:[C语言分别输出]

下一篇:C语言实现菱形输出