简体   繁体   中英

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.

char str[100];
while (str != NULL)

str is treated as a pointer to the first character in the array, so its value never changes, which means the loop will never terminate.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM