I want to directly push a character array into the standard input stream stdin
, but cannot think of a syntax that works. The closest I can think of is
freopen("input.txt", "r", stdin);
which reads the contents from a file "input.txt" into the FILE pointer stdin. But I don't like this approach because 1) it relies on creating an additional file, 2) I have to worry about creating one file for each of such requests, which can turn into a ton of txt files in a folder just for this simple purpose of assigning some character array to stdin.
Is there a better, more elegant way of doing this?
CodePudding user response:
You're mistaken about this assumption:
which reads the contents from a file "input.txt" into the FILE pointer stdin.
This is not what freopen
does! What this does is replacing the file/connection of stdin
itself.
This might be a perfectly legitimate thing to do, specifically if your program isn't expecting to have its input being redirected by its creating process.
Within the C standard library you're somewhat limited in what you can do. But if you're allowed to use POSIX syscalls, then you could to the following:
dup
the file descriptor ofstdin
into a temporary.- create an anonymous pipe using the
pipe
syscall. dup2
the reading end of the pipe over thestdin
file descriptor.write
the character array to the writing end of the pipe.- restore
stdin
bydup2
the file descriptor saved in step 1) overstdin
- close the temporary file descriptor obtained in 1