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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值