c - 从 C 程序内部写入 stdin

标签 c stdin

我正在尝试打开一个 .txt 文件并将其内容放入标准输入。我知道你可以:

myapp < input.txt

但我想在程序中多次使用相同的内容,我认为使用这种方法会消耗标准输入内容,不能再次使用。

我想测试一个从 stdin 读取的函数,作为我正在尝试的示例:

void myFunction(int number)
{
    // The function already writen reads from stdin using the argument.
}

void fillStdin(void)
{
    FILE* myFile;
    myFile = fopen("myfile.txt", "r");

    // Put the content of the file in stdin

    fclose(myFile);
}


int main(void)
{
    int myArray[5] = {1, 2, 3, 4, 5};
    for (int i = 0; i < 5; i++)
    {
        fillStdin();
        myFunction(myArray[i]);
    }

    return 0;
}

最佳答案

无需修改您的代码。像这样执行你的程序(假设你使用的是 Unix):

while true; do cat input.txt; done | myapp

这将一遍又一遍地将 input.txt 提供给您的 stdin。考虑到您需要弄清楚每次循环结束的时间,因为 stdin 永远不会以这种方式结束。

关于c - 从 C 程序内部写入 stdin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29896974/

相关文章:

c - 如何运行 python 脚本并在 C 中将参数传递给它

php - 带括号的正则表达式

python - 写入标准输入并正确打印结果

python - 如何在 Python 中将数据从不同的本地/远程进程流式传输到程序的 STDIN 中?

C/Assembler - 在没有堆栈的单用户、单任务操作系统中返回代码

c - 为什么如果我重定向文件上的 STD_OUT 并写入 STD_OUT 文件仍然为空?

c++ - 混合外部和常量

c - 非 STDIN 输入上的 scanf

node.js - 简单的是/否脚本会产生奇怪的行为

c - 实现 scanf 的替代方案