LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
12
返回列表 发新帖
楼主: pandalcg

急求 ->如何重定向stdout到一个char指针?

[复制链接]
 楼主| 发表于 2003-12-9 22:50:13 | 显示全部楼层

谢谢大家了!!

这么热心!   感激...
看来一定要用文件转了, 可是在其他的计算机上未必有写的权限呀, 嗯..有没有什么办法可以直接读出来吗?
发表于 2003-12-10 12:26:19 | 显示全部楼层
有未命名管道的
man pipe
发表于 2003-12-11 18:11:43 | 显示全部楼层
最初由 _z_ 发表
use "dup2" to redirect the STDOUT_FILENO to other file,
then read the information from file to string

example:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>

void err_exit(const char * str)
{
  fprintf(stderr,"%s\n",str);
  exit(1);
}

int main(int argc,char ** argv)
{
  int fd;
  char buf[]="zxcvbnm";
  char zzz[16];

  if((fd=open("./1.txt",O_RDWR|O_CREAT))<0)
    err_exit("error to open file!");
  
  dup2(fd,STDOUT_FILENO);

  if(write(STDOUT_FILENO,buf,sizeof(buf))<0)
    err_exit("error to open file!");

  lseek(STDOUT_FILENO,0,SEEK_SET);

  if(read(STDOUT_FILENO,zzz,sizeof(buf))<0)
    err_exit("error to open file!");

  /*did i get it?*/
  fprintf(stderr,"%s\n",zzz);

  return 0;
}

重定向到PIPE中,而不是一个文件。这样做更好。
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表