PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 18, 2022

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

 August 18, 2022     c, file-io, output, printf     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

1,217,733

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © 2025 PHPFixing