c - 如何将标准输出重定向到 ANSI C 中的字符串

标签 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 中浪费大量时间。

如何在不重定向到临时文件的情况下将标准输出重定向到 C 语言中的字符串?

这可能吗?谢谢。

环境: Windows 和 GCC

最佳答案

标准输出可以通过 popen 重定向常规:

#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() */
   ...
}

关于c - 如何将标准输出重定向到 ANSI C 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19288859/

相关文章:

c - 使用 write() 系统调用写一个完整的缓冲区

c - 2 个管道,一个 fork ,bc 和 execlp (C)

java - 我将如何制作一个包含括号的字符串? - java

javascript - 在字符串中的字符之间添加空格

http - 为什么 CORS 规范不允许重定向?

wordpress - 如何将两个 wordpress 页面重定向到 https?

C Linux pthreads : sending data from one thread to another using shared memory gives unexpected result

c - MPI 中的雅可比松弛

string - 在 bash 中使用随机可打印字符串创建特定大小的文件

asp.net - CustomErrors DefaultRedirect 到 Default.aspx 不起作用