Thursday, August 18, 2022

[FIXED] How to write to a file using open() and printf()?

Issue

I am opening a file with open(), and need to print to that file using printf with no output to the console. How do I do this? I can successfully create the file, and printf to the console, but that is not correct.

int main(int argc, char *argv[]) {
    int fd;
    char *name = "helloworld";
    fd = open(name, O_CREAT);

    char *hi = "Hello World";
    printf("%s\n", hi);

    close(fd);
    exit(0);
}

I need the program to have no output to the console, but if I look at the file helloworld, it should have "Hello World" written inside. Such as:

prompt> ./hello
prompt> more helloworld
   Hello World

Solution

There's a trick to this.

You need to duplicate the open file descriptor to file descriptor 1, i.e. stdout. Then you can use printf:

int main(int argc, char *argv[]){

    int fd;
    char *name = "helloworld";
    fd = open(name, O_WRONLY | O_CREAT, 0644);
    if (fd == -1) {
        perror("open failed");
        exit(1);
    }

    if (dup2(fd, 1) == -1) {
        perror("dup2 failed"); 
        exit(1);
    }

    // file descriptor 1, i.e. stdout, now points to the file
    // "helloworld" which is open for writing
    // You can now use printf which writes specifically to stdout

    char *hi = "Hello World";
    printf("%s\n", hi);

    exit(0);

}


Answered By - dbush
Answer Checked By - Marie Seifert (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.