首页 > 解决方案 > 打印到文本文件但文件仍然为空

问题描述

#include <stdio.h> //for printf
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include  <stdio.h>
//#define STDOUT_FILENO 1
// define STDERR_FILENO 2
int main(){
    // mode_t mode = S_IROTH | S_IRUSR | S_IWUSR;
    mode_t mode = S_IRUSR | S_IWUSR;
    
    close(1);
    int fildes = open("hello_world.txt", O_CREAT | O_TRUNC | O_RDWR, mode);
    printf("Hi! My Name is \n" );
    close(fildes);
    return 0;
}

据我所知,“嗨!我的名字是”应该打印到“hello_world.txt”。它在我教授提供的 Linux 虚拟机中运行良好。但是在我的机器中(我在 vscode 中使用远程 WSL),“hello_world.txt”是空的。我可以解决这个问题吗?

标签: c

解决方案


printf不一定写什么。通常,它缓冲数据并延迟writes 直到缓冲区已满。 stdout进程退出时会自动刷新,但在此之前您已经关闭了文件描述符,因此write失败。fflush(stdout)在关闭底层文件描述符之前尝试。(这假设 hackyopen实际上为您提供了标准输出的底层文件描述符。这应该发生并且在大多数情况下会发生,但肯定不能保证。freopen如果您想可靠地执行此操作,您应该使用。)


推荐阅读