C小程序 - 将stdin定向到文件

4731阅读 0评论2012-10-29 niannian
分类:C/C++

将stdin定向到文件
1. close(0),即将标准输入的连接断开
2. open(filename, O_RDONLY)打开一个想连接到stdin上的文件。当前的最低可用文件描述符是0,所以打开的文件将被连接到标准输入上去。这时候任何想从标准输入读取数据的函数都将从次文件中读入。

  1. #include    <stdio.h>
  2. #include    <fcntl.h>

  3. main()
  4. {
  5.     int    fd ;
  6.     char    line[100];

  7.     /* read and print three lines */

  8.     fgets( line, 100, stdin ); printf("%s", line );

  9.     /* redirect input */

  10.     close(0);
  11.     fd = open("/etc/passwd", O_RDONLY);
  12.     if ( fd != 0 ){
  13.         fprintf(stderr,"Could not open data as fd 0\n");
  14.         exit(1);
  15.     }

  16.     /* read and print three lines */

  17.     fgets( line, 100, stdin ); printf("%s", line );
  18. }
第二种方法:
1. fd=open(file),打开stdin将要重定向的文件,这时候文件的描述符不是0,因为0被stdin占据。
2. close(0), 现在0已经空闲
3. dup(fd), 将fd做一个复制,这时候将使用文件描述符0,也就是将打开的文件和文件描述符0也关联起来。这时候文件有两个描述符号,fd和0
4. close(fd), 关闭fd,这时候任何想从标准输入读取数据的函数都将从次文件中读入。

  1. #include    <stdio.h>
  2. #include    <fcntl.h>

  3. /* #define    CLOSE_DUP        /* open, close, dup, close */
  4. /* #define    USE_DUP2    /* open, dup2, close */

  5. main()
  6. {
  7.     int    fd ;
  8.     int    newfd;
  9.     char    line[100];

  10.     /* read and print three lines */

  11.     fgets( line, 100, stdin ); printf("%s", line );

  12.     /* redirect input */
  13.     fd = open("data", O_RDONLY);    /* open the disk file    */
  14. #ifdef CLOSE_DUP
  15.     close(0);
  16.     newfd = dup(fd);        /* copy open fd to 0    */
  17. #else
  18.     newfd = dup2(fd,0);        /* close 0, dup fd to 0 */
  19. #endif
  20.     if ( newfd != 0 ){
  21.         fprintf(stderr,"Could not duplicate fd to 0\n");
  22.         exit(1);
  23.     }
  24.     close(fd);            /* close original fd    */

  25.     /* read and print three lines */

  26.     fgets( line, 100, stdin ); printf("%s", line );
  27. }
上一篇:kpartx 命令
下一篇:C小程序 - fork,在子进程中重定向输出,然后执行shell程序