while( (reader=fread(array, sizeof(char), size, stdin))>0 )
I have this kind of guard what I need is within this cycle when 开发者_JAVA百科I call a function I want to simulate that I'm giving my fread
something.
Sorry about the scary English.
@Fritschy's answer with @Ben Voigt's comment constitute the portable solution.
If you're on Unix/Linux/similar, you can actually write things into stdin
by
int p[2];
// error return checks omitted
pipe(p);
dup2(p[0], STDIN_FILENO);
FILE *stdin_writer = fdopen(p[1], "w");
Now write into stdin_writer
.
See pipe
, dup2
, fdopen
in the POSIX standard.
You can replace stdin with a FILE* of your choice for testing:
FILE *test = fopen("mytestFile.txt", "r");
/* your code here... */
Or when need of stdin:
FILE *test = stdin;
/* your code here... */
This answer is constructed on @Ben Voigt's comment.
Create input.txt
with some text and main.c
with this code.
The code will inject input.txt
text into stdin and then send it into stdout.
#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;
}
精彩评论