Skip to main content

Flexible reading

Posted in

Experience, is such a thing... wait, I have written this somewhere already... Oh, that's right, in my previous post. Then, lets get right to the problem.

I always loved such utils like grep. You want to grep the file? Grep it:

grep "MyWord" file.txt

You want to grep some output? Grep it:

my_mystic_script.sh | grep "MyWord"

Very handy...

Many of you already know how to do this in your own application. But, nevertheless, I will explain it, so that at least I know where to look for when I need this.

We know for sure, that if a file comes as a parameter we will read some data from it, e.g.

int fd = open(argv[1], O_RDONLY);
...
read(fd, buf, SIZE);

But what if no file is specified?
That's right, if no file is specified, then we just override fd with the descriptor of stdin.

int fd;
if (1 < argc)
{
    fd = open(argv[1], O_RDONLY);
}
else
{
    fd = STDIN_FILENO;
}
 
// and then do whatever you have to do...

Nice and easy, that's what I like.

Post new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
_at_strophe: