我正在尝试打开一个 .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/