如何将标准输出重定向到ANSI C中的字符串
我是学习C语言的初学者:-) 我在stackoverflow中搜索了如何解决这个问题,但我什么都不懂-( 在发布此线程之前,我总是将stdout重定向到一个文件,然后使用如何将标准输出重定向到ANSI C中的字符串,c,string,redirect,stdout,C,String,Redirect,Stdout,我是学习C语言的初学者:-) 我在stackoverflow中搜索了如何解决这个问题,但我什么都不懂-( 在发布此线程之前,我总是将stdout重定向到一个文件,然后使用fread system ("print.exe > tempfile.tmp"); FILE *fp = fopen ( tempfile.tmp , "rb" ); char Str[Buf_Size]; fread (Str,sizeof(char),Buf_Size,fp); 如果这样做,将在文件I/O中浪费大量
fread
system ("print.exe > tempfile.tmp");
FILE *fp = fopen ( tempfile.tmp , "rb" );
char Str[Buf_Size];
fread (Str,sizeof(char),Buf_Size,fp);
如果这样做,将在文件I/O中浪费大量时间
如何将标准输出重定向到C语言中的字符串而不重定向到临时文件
可能吗?谢谢
环境:
Windows和GCC
在Unix中,您将:
- 创建一个
管道
子进程fork
- 家长:
- 关闭管道的写入端
- 开始从管道读取数据
- 孩子:
- 关闭管道的读取端
- 关闭
stdout
是fd 1的写入端管道dup2
是新程序exec
#包括
...
文件*fp;
智力状态;
字符路径[path_MAX];
fp=popen(“ls*”,“r”);
如果(fp==NULL)
/*处理错误*/;
while(fgets(path,path_MAX,fp)!=NULL)
printf(“%s”,路径);
状态=pclose(fp);
如果(状态==-1){
/*pclose()报告的错误*/
...
}否则{
/*使用wait()下描述的宏按顺序检查“状态”
确定popen()执行的命令的成功/失败*/
...
}
如果您在POSIX ish环境中,您可以通过文件*fp=popen(“print.exe”,“r”);
读取print.exe的输出。如果您在Microsoft ish系统中,您可以使用\u popen()
代替windows中的popen()
@Jonathon Reinhart在windows中该怎么做?查看此线程
#include <stdio.h>
...
FILE *fp;
int status;
char path[PATH_MAX];
fp = popen("ls *", "r");
if (fp == NULL)
/* Handle error */;
while (fgets(path, PATH_MAX, fp) != NULL)
printf("%s", path);
status = pclose(fp);
if (status == -1) {
/* Error reported by pclose() */
...
} else {
/* Use macros described under wait() to inspect `status' in order
to determine success/failure of command executed by popen() */
...
}