简体   繁体   中英

How to reuse (rewind) a redirected file in C

I input a text file into my C program by using the < I/O redirection in the terminal:

MyProgram.exe < "data.txt"

And then use getchar() and scanf() in my code to read from the redirected input. However, as this is a redirected file, I can't use a C file pointer to rewind the buffer.

(I want to count the number of lines in a file of an arbitrary size so I can initialize an array, then I want to re-read the file using getchar() and/or scanf() ).

How do I achieve a rewind or flush when using redirected input?

However, as this is a redirected file, I cant use ac file pointer to rewind the buffer.

Sure you can! And it's really easy. When a file is being redirected to standard input, stdin is a file, so you can treat it just like any other file:

rewind(stdin);

But keep in mind that this will only work if standard input is being redirected from a file . It won't work if standard input is from the terminal or a pipe (eg, cat file.txt | myapp ).

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