C++ C-调用函数时需要在代码中模拟stdin
我有这种保护,我需要的是在这个周期内,当我调用一个函数,我想模拟我给我的fread一些东西C++ C-调用函数时需要在代码中模拟stdin,c++,c,stdin,C++,C,Stdin,我有这种保护,我需要的是在这个周期内,当我调用一个函数,我想模拟我给我的fread一些东西 抱歉,英语太可怕了。您可以用自己选择的文件*替换stdin进行测试: while( (reader=fread(array, sizeof(char), size, stdin))>0 ) 或在需要标准DIN时: FILE *test = fopen("mytestFile.txt", "r"); /* your code here... */ @Fritschy的回答和@Ben Voigt的评
抱歉,英语太可怕了。您可以用自己选择的文件*替换stdin进行测试:
while( (reader=fread(array, sizeof(char), size, stdin))>0 )
或在需要标准DIN时:
FILE *test = fopen("mytestFile.txt", "r");
/* your code here... */
@Fritschy的回答和@Ben Voigt的评论构成了便携式解决方案 如果您使用的是Unix/Linux/similor,您实际上可以通过 现在写进stdin_writer
请参阅POSIX标准中的。此答案基于@Ben Voigt的评论。 使用此代码创建带有一些文本的input.txt和main.c。 代码将把input.txt文本注入stdin,然后将其发送到stdout
int p[2];
// error return checks omitted
pipe(p);
dup2(p[0], STDIN_FILENO);
FILE *stdin_writer = fdopen(p[1], "w");
根据C标准,sizeofchar保证为1。如果希望使代码保持灵活性,可以编写数组[0]的大小,如果更改数组的类型,该大小将相应更改。否则,我就用1。但这是我个人的偏好。我如何在执行时与我的守卫一起工作,比方说我调用i SIGINT,我想在等待stdin输入时弹出,但我在等待输入…你可以打开文件,或者使用select2或poll2。然而,这些仅适用于普通FD。您可以使用fileno3函数从文件*获取FD。更多信息请参见手册页;或者,你甚至可以打电话给弗罗普。不推荐用于生产代码,尽管在单元测试中它可能会很有用。
int p[2];
// error return checks omitted
pipe(p);
dup2(p[0], STDIN_FILENO);
FILE *stdin_writer = fdopen(p[1], "w");
#include <stdlib.h>
#include <stdio.h>
int main()
{
freopen("input.txt", "r", stdin);
unsigned int BLOCK_SIZE = 3;
char buffer[BLOCK_SIZE];
for(;;) {
size_t bytes = fread(buffer, sizeof(char),BLOCK_SIZE,stdin);
fwrite(buffer, sizeof(char), bytes, stdout);
fflush(stdout);
if (bytes < BLOCK_SIZE)
if (feof(stdin))
break;
}
return 0;
}