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

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/hkhl_235/article/details/79585015
/* 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;
}




猜你喜欢

转载自blog.csdn.net/hkhl_235/article/details/79585015
dup
今日推荐