欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > c语言输出重定向到文件

c语言输出重定向到文件

2025/2/13 7:22:19 来源:https://blog.csdn.net/jiangliuhuan123/article/details/145584154  浏览:    关键词:c语言输出重定向到文件

在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;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com