gpt4 book ai didi

c - c中的匿名流

转载 作者:太空宇宙 更新时间:2023-11-04 00:42:54 24 4
gpt4 key购买 nike

我可以在 c 中创建一个匿名流吗?我不想在文件系统上创建一个新文件,只需要一个函数可以写入的流,而另一个函数可以从中读取。不是 c++,c。

最佳答案

也许您正在寻找管道。

将您的 STDOUT 转发到管道。

然后另一个应用程序将从管道中读取。

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

#define RDR 0
#define WTR 1

char ** parseargs(char *string);

int main(void){
char mode = 'r';
char prog[50] = "/bin/ps --version";
char **argv;
int p[2];
pid_t pid;
FILE *readpipe;
int pipein, pipeout;
char buf;


/* create the pipe */
if(pipe(p) != 0){
fprintf(stderr, "error: could not open pipe\n");
}

pipein = p[RDR];
pipeout = p[WTR];

if((pid = fork()) == (pid_t) 0){



close(pipein);

dup2(pipeout, 1);
close(pipeout);


if(execv(argv[0], argv) == -1){
fprintf(stderr, "error: failed to execute %s\n", argv[0]);
}
_exit(1);
}

close(pipeout);


readpipe = fdopen(pipein, &mode);

while(!feof(readpipe)){
if(1 == fread(&buf, sizeof(char), 1, readpipe)){
fprintf(stdout, "%c", buf);
}
}


return 0;
}

关于c - c中的匿名流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1520289/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com