在C语言中,可以通过重定向标准输出来将程序的输出写入文件,而不是显示在终端上。以下是几种常见的方法:
方法1:使用 freopen 函数
freopen 函数可以将标准输出重定向到文件。
#include <stdio.h>int main()
{// 打开文件用于写入,如果文件不存在则创建freopen("output.txt", "w", stdout);// 现在所有的 printf 输出都会写入到 output.txt 文件中printf("Hello, World!\n");printf("This is a test.\n");// 关闭文件fclose(stdout);return 0;
}
方法2:使用 fprintf 函数
fprintf 函数可以直接将输出写入指定的文件。
#include <stdio.h>int main()
{FILE *file = fopen("output.txt", "w");if (file == NULL) {perror("Failed to open file");return 1;}// 使用 fprintf 将输出写入文件fprintf(file, "Hello, World!\n");fprintf(file, "This is a test.\n");// 关闭文件fclose(file);return 0;
}
方法3:使用 dup2 函数
dup2 函数可以将文件描述符复制到标准输出文件描述符(通常是1),从而实现重定向。
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>int main()
{int file = open("output.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);if (file < 0) {perror("Failed to open file");return 1;}// 将标准输出重定向到文件dup2(file, STDOUT_FILENO);// 现在所有的 printf 输出都会写入到 output.txt 文件中printf("Hello, World!\n");printf("This is a test.\n");// 关闭文件close(file);return 0;
}