2
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.

2
  • 5
    sizeof(char) is guaranteed to be 1 by the C standard. If you want to keep the code flexible, you could write sizeof 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.) Commented Dec 8, 2010 at 23:41
  • Change fread to my_fread and write my_fread to do whatever you want. Commented Sep 1, 2021 at 16:42

3 Answers 3

4

@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.

Sign up to request clarification or add additional context in comments.

Comments

3

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... */

3 Comments

how can i make this work with my guard in execution time, lets say i call i SIGINT and i want to pop out of my while but im waiting for the stdin input...
You could open files O_NONBLOCK or use select(2) or poll(2). Those however work only on plain FDs. You can get the FD from a FILE* with the fileno(3) function. See the manpages for more ;)
or, you could even call freopen on stdin. Not recommended for production code, though in a unit test it could be useful.
3

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.