I want stdin to be redirected to a string of text supplied in my program. I want to write the string of text to a temporary file and then point stdin to that file. I'm a little unsure about this code because it seems to blend low level function calls like write()
and dup()
with higher level function calls like fclose()
. Is this the correct approach?:
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);
EDIT
As per a suggestion in the comments, I tried approaching this problem with pipes. If I want to use pipes, would this be the correct approach? I still want feedback on the first approach as well:
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]);