while( (reader=fread(array, sizeof(char), size, stdin))>0 )
I have this kind of guard what I need is within this cycle when 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.
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... */
freopen on stdin. Not recommended for production code, though in a unit test it could be useful.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;
}
sizeof(char)is guaranteed to be 1 by the C standard. If you want to keep the code flexible, you could writesizeof array[0], which will change appropriately if you change the type of the array. Otherwise, I'd just use 1. (But it's personal preference.)freadtomy_freadand writemy_freadto do whatever you want.