#include <stdio.h>
#include <errno.h>

int main() {
    if(!freopen("output.txt", "w", stdout)) {
        printf("Error: %s\n", strerror(errno));
        return errno;
    }
    printf("Hello world!\n");
    return 0;
}

在这个例子中,我们使用 freopen() 函数把标准输出重定向到一个名为 "output.txt" 的文件。如果 freopen() 函数失败,它会返回 NULL,这时我们输出一个错误信息,包含错误代码。注意在输出字符串后要加上换行符 \n

如果 freopen() 函数成功,我们就可以像平常一样使用 printf() 函数输出 "Hello world!" 到标准输出。最后返回 0 表示程序正常结束。

用 C 语言写个程序输出 Hello world!当标准输出重定向到不可写的目标时返回错误代码。

原文地址: https://www.cveoy.top/t/topic/Cq8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录