Search code examples
chttp-redirectpiping

Error piping/redirecting from a file or command in windows


I made a program that I then used to create a file from its output, now I want to make one of several programs to run redirecting that file (or piping the output of the other programs to it). I used the following code as a test for the first program

int main (int argc, char* argv[])
{

    long long int n = 0;
    char str[100];

    while (str != NULL)
    {
        fscanf(stdin,"%s\0", str);
        printf("%lld\t%s\n", n, str);

        n++;
    }

    return 0;

}

The program executes correctly until the last line of the redirected file or piped output, which then keeps repearing infinitely until I stop the execution with ctrl-c (Windows). I don't know why this happens, I tried flushing stdin, stdout and everything that I had think of and no luck.

What I am doing wrong or missing ?

Thanks in advance.


Solution

  • while (str != NULL)
    {
        fscanf(stdin,"%s\0", str);
        printf("%lld\t%s\n", n, str);
    
        n++;
    }
    

    replaced by

    while (scanf("%s", str) != EOF)
    {
        printf("%lld\t%s\n", n, str);
        n++;
    }
    

    Solved the problem.