将stdin重定向到临时文件?

时间:2013-11-21 17:29:54

标签: c unix io-redirection temporary-files

我希望stdin被重定向到我程序中提供的一串文本。我想将文本字符串写入临时文件,然后将stdin指向该文件。我对此代码有点不确定,因为它似乎将write()dup()等低级函数调用与fclose()等更高级函数调用混合在一起。这是正确的方法吗?:

char* buffer = "This is some text";
int nBytes = strlen(buffer);
FILE* file = tmpfile();
int fd = fileno(file);
write(fd,buffer,nBytes);
rewind(file);
dup2(fd,0);
fclose(file);

修改

根据评论中的建议,我尝试用管道解决这个问题。如果我想使用管道,这是正确的方法吗?我仍然想要第一种方法的反馈:

int fd[2];
pipe(fd); // For sake of simplicity assume returns 0 (no error).
char* buffer = "This is some text";
int nBytes = strlen(buffer);
write(fd[1],buffer,nBytes);
close(fd[1]);
dup2(fd[0],0);
close(fd[0]);

0 个答案:

没有答案