Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write in stdin from inside a program in C

Tags:

c

stdin

I am trying to open a .txt file and put its contents in the standard input. I know you can do:

myapp < input.txt

but i want to use the same content several times inside the program and i think that with this method the stdin content is consumed and can not be used again.

I want to test a function that reads from stdin, just as an example of what i am trying:

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;
}
like image 292
wallek876 Avatar asked Nov 21 '22 20:11

wallek876


1 Answers

No need to modify your code. Just execute your program as this (assuming you are using Unix):

while true; do cat input.txt; done | myapp

This will feed input.txt to your stdin over and over again. Take into account that you will need to figure out when you have reached the end of each recurrence, as stdin will never EOF this way.

like image 113
mcleod_ideafix Avatar answered Nov 24 '22 08:11

mcleod_ideafix