如何使用open()和printf()写入文件? [英] How to write to a file using open() and printf()?

查看:84
本文介绍了如何使用open()和printf()写入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我需要程序没有输出到控制台的功能,但是如果我查看文件helloworld,它的内部应该写有"Hello World".如:

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

推荐答案

有一个窍门.

您需要将打开的文件描述符复制到文件描述符1,即stdout.然后您可以使用printf:

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);

}

这篇关于如何使用open()和printf()写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆