免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
12
最近访问板块 发新帖
楼主: tmp
打印 上一主题 下一主题

寻一个不用管道就能写文件的命令 [复制链接]

论坛徽章:
1
2015年辞旧岁徽章
日期:2015-03-03 16:54:15
11 [报告]
发表于 2010-11-17 14:51 |只看该作者
以下这段代码可以重定向。我在C/C++板块看到的。
  1. #include <unistd.h>
  2. #include <stdio.h>
  3. #include <errno.h>
  4. #include <fcntl.h>
  5. #include <string.h>
  6. #include <sys/types.h>
  7. #include <sys/stat.h>

  8. #define BUFFER_SIZE 1024

  9. int main(int argc, char **argv)
  10. {
  11.    int fd;
  12.    char buffer[BUFFER_SIZE];
  13.    if(argc!=2)
  14.    {
  15.      fprintf(stderr,"Usage:%s outfilename\n\a",argv[0]);
  16.      exit(1);
  17.    }
  18.    if((fd=open(argv[1],O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)) \
  19.        == -1)
  20.    {
  21.      fprintf(stderr,"Open %s Error:%s\n\a", argv[1],strerror(\
  22.                 errno));
  23.      exit(1);
  24.    }
  25.    if(dup2(fd,STDOUT_FILENO) == -1)
  26.    {
  27.      fprintf(stderr,"Redirect Standard Out Error:%s\n\a",\
  28.              strerror(errno));
  29.      exit(1);
  30.    }
  31.    fprintf(stderr,"Now, please input string");
  32.    fprintf(stderr,"(To quit use CTRL+D)\n");
  33.    while(1)
  34.    {
  35.      fgets(buffer,BUFFER_SIZE,stdin);
  36.      if(feof(stdin)) break;
  37.      write(STDOUT_FILENO, buffer, strlen(buffer));
  38.    }
  39.    exit(0);
  40. }
复制代码

论坛徽章:
0
12 [报告]
发表于 2010-11-18 14:17 |只看该作者
直接用编辑器打开,写进去
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP