jun
jun

Reputation: 133

Printing to text file but file remains empty

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

From what I learned, "Hi! My Name is" should be printed to "hello_world.txt". It works well in Linux virtual machine which my professor provided. But in my machine (I'm using remote WSL in vscode), "hello_world.txt" is empty. Can I fix this problem?

Upvotes: -1

Views: 359

Answers (1)

William Pursell
William Pursell

Reputation: 212494

printf does not necessarily write anything. Typically, it buffers data and defers writes until the buffers are full. stdout is automatically flushed when the process exits, but you've closed the file descriptor before that happens, so the write fails. Try fflush(stdout) before you close the underlying file descriptor. (This assumes that the hacky open actually gives you the underlying file descriptor of stdout. That should happen and in most cases will, but it certainly is not guaranteed. You should use freopen if you want to do this reliably.)

Upvotes: 3

Related Questions