简体   繁体   English

如何在c中直接将字符数组赋值给stdin?

[英]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 系统调用,那么你可以执行以下操作:

  1. dup the file descriptor of stdin into a temporary.dup的文件描述符stdin到临时文件中。
  2. create an anonymous pipe using the pipe syscall.使用pipe系统调用创建匿名 pipe。
  3. dup2 the reading end of the pipe over the stdin file descriptor. dup2通过stdin文件描述符读取 pipe 的末端。
  4. write the character array to the writing end of the pipe. write字符数组写入pipe的写端。
  5. restore stdin by dup2 the file descriptor saved in step 1) over stdin通过dup2恢复stdin在步骤 1) 中保存的文件描述符通过stdin
  6. close the temporary file descriptor obtained in 1关闭1中得到的临时文件描述符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM