stdin and pipes
Hi,
I was trying to learn about pipes and standard input/output streams in linux. So I wrote a simple program. Source Code: Code:
#include <stdio.h> My output was: Enter string :Linux Enter string :Linux Enter string :Linux Enter string :Linux Enter string :Linux Enter string :Linux Enter string :Linux Enter string :Linux : : This goes on forever. What I was expecting was that the program would print Linux once and then wait for next input from stdin. This error probably might be occuring because the word Linux is still on the stdin of a.out and it is reading the same thing every second (just my guess). So I tried removing the infinite loop in the code, but in that case if I do "uname | ./a.out" it works. But if I do some command that prints mulitple lines of text like "ls | ./a.out" only the first file name is printed and a.out exits. Can anyone suggest any method to solve this problem. Thanks |
Hi there,
Quote:
Quote:
Quote:
Code:
while (!feof(stdin)) [X] Doc CPU |
Thanks for the detailed answer. I have been trying to find the answer for hours :newbie: . I didn't understand some part of it though.
Quote:
Quote:
Also wasn't fflush(NULL) supposed to take care of stale values inside STDIN. STDOUT |
Quote:
|
Quote:
Code:
#include <stdio.h> |
Hi there,
Quote:
Quote:
Well, look: fgets() reads until there is either an end-of-file condition, or a line feed. In your situation, the output of uname that you pipe into your program ends with a line feed. So fgets() reads everything, including the line feed, and then returns that data. At that moment, feof(stdin) doesn't catch yet, because you have read up to the end of the stream, but not beyond. End-of-file is recognized only when you try to read past the end. And that happens in lap 2 of your loop. That's not nice, because it forces the programmer to produce "spaghetti code". You can revert to your "while (1)" as the heading of your loop, but now you must supply something that ends the loop as soon as you know it should be ended - and that's after the fgets() call. Insert another line after the fgets() call: Code:
if (feof(stdin)) Quote:
[X] Doc CPU |
Hi there,
Quote:
Quote:
[X] Doc CPU |
Thanks everyone especially Doc CPU for your answers.
Quote:
Quote:
Quote:
|
Oops I didn't see Doc CPU's last reply :)
|
Better Code:
Code:
#include <stdio.h> |
Hi there,
Quote:
[X] Doc CPU |
The rtn type is 'void *' so that you CAN cast it to the type you require, which you should do for robust code. It also makes it clearer for the next guy ;)
|
Hi there,
Quote:
Quote:
[X] Doc CPU |
Why use malloc() for a fixed-size string that's only used for the lifetime of a function? use an array:
Code:
char str[80]; |
I guess I should have been clearer when I wrote "Better Code". I wrote that in response to DocCPU's earlier comment to feof forcing developers to write spaghetti code.
Quote:
Quote:
|
All times are GMT -5. The time now is 01:35 AM. |