redirect output from stdout to a string?

你离开我真会死。 提交于 2019-11-29 10:51:52
char string[SIZE];
freopen("/dev/null", "a", stdout);
setbuf(stdout, string);

see freopen and setbuf for their definitions

This should work on UNIX systems:

// set buffer size, SIZE
SIZE = 255;

char buffer[SIZE];
freopen("/dev/null", "a", stdout);
setbuf(stdout, buffer);
printf("This will be stored in the buffer");
freopen ("/dev/tty", "a", stdout);

You could write to a pipe, and read from it into shared memory (that is, if you can't use the pipe instead of the string in shared memory).

with shm_open you can have a file descriptor pointing to a shared memory and pass it to dup2 function as below:

int fd = shm_open("shm-name", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
dup2(fd, STDOUT_FILENO);
fprintf(stdout, "This is string is gonna be printed on shared memory");

And after all seek the shared memory to the beginning (with lseek read it and save it to a string; But be careful

Also you can find an example of buffering into pipe in Here

Carlos

In order to do a simple redirection of stdout to a memory string, just do this:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PATH_MAX 1000

int main()
{
    FILE *fp;
    int status;
    char path[PATH_MAX];

    fp = popen("ls ", "r");

    if (fp == NULL)  return 0;


    while (fgets(path, PATH_MAX, fp) != NULL)
        printf("\nTest=> %s", path);

    status = pclose(fp);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!