dup(应用dup将printf函数重定向到文件当中)

/* printf重定向到某个文件中 */
/* dup()函数功能: */

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>

int main()
{
    /* 函数:  int fd = dup(oldfd) */
    /* The dup() system call creates a copy of the file descriptor oldfd, 
     * using the lowest-numbered unused descriptor for the new descriptor.
     * 返回值是当前最小未使用的fd, 该返回fd的功能则是oldfd的功能则是
     */
    int nfd = dup(STDOUT_FILENO);   //fd = 3 功能是标准输出 ,当前最小未使用fd为3
    close(STDOUT_FILENO);           //文件描述符1被关闭

    int fd = open("output.txt", O_CREAT|O_RDWR, 0744);   //此时打开fd = 1, 因为无人占用1, fd指向文件output.txt
    if(fd == -1)
    {
        perror("open");
        exit(1);
    }

    /*终端输出*/
    write(nfd, "nfd\n", 4);

    /*文件输出*/
    write(fd, "fd\n", 3);
    write(STDOUT_FILENO, "stdout\n", 7);
    printf("fd = %d\n", fd);
    printf("hello ! How are you ? I'm fine! And you ? I'm ok!\n");

    //close(fd)        //为什么加上这句话,printf就不会在文件里输出?
                       //这是一个问题.

    return 0;
}




评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值