[英]How to directly assign character array to stdin in c?
I want to directly push a character array into the standard input stream stdin
, but cannot think of a syntax that works.我想直接将字符数组推入标准输入 stream
stdin
,但想不出有效的语法。 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.它将文件“input.txt”中的内容读取到 FILE 指针标准输入中。 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.
但我不喜欢这种方法,因为 1) 它依赖于创建一个额外的文件,2) 我不得不担心为每个这样的请求创建一个文件,这可能会在一个文件夹中变成大量的 txt 文件。将一些字符数组分配给标准输入的简单目的。
Is there a better, more elegant way of doing this?有更好、更优雅的方法吗?
You're mistaken about this assumption:你误解了这个假设:
which reads the contents from a file "input.txt" into the FILE pointer stdin.
它将文件“input.txt”中的内容读取到 FILE 指针标准输入中。
This is not what freopen
does!这不是
freopen
所做的! What this does is replacing the file/connection of stdin
itself.它所做的是替换
stdin
本身的文件/连接。
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.在 C 标准库中,您可以做的事情有些受限。 But if you're allowed to use POSIX syscalls, then you could to the following:
但是如果你被允许使用 POSIX 系统调用,那么你可以执行以下操作:
dup
the file descriptor of stdin
into a temporary.dup
的文件描述符stdin
到临时文件中。pipe
syscall.pipe
系统调用创建匿名 pipe。dup2
the reading end of the pipe over the stdin
file descriptor. dup2
通过stdin
文件描述符读取 pipe 的末端。write
the character array to the writing end of the pipe. write
字符数组写入pipe的写端。stdin
by dup2
the file descriptor saved in step 1) over stdin
dup2
恢复stdin
在步骤 1) 中保存的文件描述符通过stdin
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.