如何使用 open() 和 printf() 写入文件?

6 c file-io printf output

我正在使用 open() 打开一个文件,并且需要使用 printf 打印到该文件,而不输出到控制台。我该怎么做呢?我可以成功创建文件,并 printf 到控制台,但这是不正确的。

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);
}
Run Code Online (Sandbox Code Playgroud)

我需要程序没有输出到控制台,但是如果我查看该文件helloworld,它应该在里面写有“Hello World”。例如:

prompt> ./hello
prompt> more helloworld
   Hello World
Run Code Online (Sandbox Code Playgroud)

dbu*_*ush 6

这有一个技巧。

您需要将打开的文件描述符复制到文件描述符 1,即stdout. 然后你可以使用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);

}
Run Code Online (Sandbox Code Playgroud)