Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1176787
  • 博文数量: 573
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 66
  • 用 户 组: 普通用户
  • 注册时间: 2016-06-28 16:21
文章分类

全部博文(573)

文章存档

2018年(3)

2016年(48)

2015年(522)

分类: LINUX

2015-12-02 16:12:56


点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <fcntl.h>

  6. ssize_t readn(int fd, void * ptr, size_t n)
  7. {
  8.         size_t nleft;
  9.         ssize_t nread;
  10.         
  11.         nleft = n;
  12.         while(nleft > 0)
  13.         {
  14.                 if((nread = read(fd, ptr, nleft)) < 0)
  15.                 {
  16.                         if(nleft == n)
  17.                                 return -1;
  18.                         else
  19.                                 break;
  20.                 }
  21.                 else if(nread == 0)
  22.                 {
  23.                         break;
  24.                 }
  25.                 nleft -= nread;
  26.                 ptr += nread;
  27.         }
  28.         return(n - nleft);
  29. }

  30. int main(int argc, char * * argv)
  31. {
  32.         printf("**************************************************\n");
  33.         int fd2;
  34.         fd2 = open("dup2.2.txt", O_CREAT|O_RDWR, 0777);
  35.         printf("fd2 = [%d]\n", fd2);
  36.         if(fd2 < 0)
  37.         {
  38.                 printf("open err!\n");
  39.                 exit(0);
  40.         }
  41.         
  42.         write(fd2, "wangxiancai\n", strlen("wangxiancai\n"));
  43.         lseek(fd2, SEEK_SET, 0); /*如果open是追加打开的,或者,write过了,这里必须用lseek*/
  44.         dup2(fd2, STDIN_FILENO);
  45.         
  46.         char buf[128];
  47.         memset(buf, 0, sizeof(buf));
  48.         char ch;
  49.         
  50.         //scanf("%c", &ch);
  51.         int ret = -1;
  52.         ret = read(STDIN_FILENO, buf, 5);
  53.         //ret = read(fd2, buf, 4);
  54.         //ret = readn(fd2, buf, 4);
  55.         printf("ret = [%d]\n", ret);
  56.         printf("buf = [%s]\n", buf);
  57.         //printf("ch = [%c]\n", ch);

  58.         printf("**************************************************\n");
  59.         int fd;
  60.         fd = open("dup2.txt", O_CREAT|O_APPEND|O_RDWR, 0777);
  61.         if(fd < 0)
  62.         {
  63.                 printf("open err!\n");
  64.                 exit(0);
  65.         }
  66.         dup2(fd, STDOUT_FILENO);
  67.         /*标准输出关闭,之后任何写到标准输出的东西,现在都写到“dup2.txt”文件中去*/
  68.         printf("wangxiancai\n"); //这句,原本想写到标准输出的语句,写到“dup2.txt”文件中去了。
  69.         

  70.         
  71.         return 0;
  72. }

阅读(423) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~