Home > Enterprise >  How to directly assign character array to stdin in c?
How to directly assign character array to stdin in c?

Time:01-07

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:

  1. dup the file descriptor of stdin into a temporary.
  2. create an anonymous pipe using the pipe syscall.
  3. dup2 the reading end of the pipe over the stdin file descriptor.
  4. write the character array to the writing end of the pipe.
  5. restore stdin by dup2 the file descriptor saved in step 1) over stdin
  6. close the temporary file descriptor obtained in 1
  • Related