-2

I need to parse the file as an argument to my C code by using cat:

cat filename | ./code -n 10

So that it works the same way as:

./code filename -n 10

Or is there any way to read the file directly through the cat command by using read syscall? I was thinking about something like this:

read([file from the cat], buf, sizeof(buf));

and maybe if I do it this way I don't need to do it like this:

fd = open(fileName, O_RDONLY);
read(fd, buf, sizeof(buf));

It s the first time I see cat used this way; I tried to google it but couldn't find anything. I am a beginner in C language and Unix; any help would be appreciated. Thank you.

  • Unclear which of the two you actually want: the *read from stdin* version or the *read from a named file* version? – wildplasser Feb 15 '21 at 19:59

1 Answers1

0

This is my first answer on stackoverflow, so bear with me...

"Running cat filename reads the contents of the specified file and writes them to standard output. | between two commands means connect standard output of the left command to standard input of the right command." cat and pipe

When you propose to read from "file from the cat"... read([file from the cat], buf, sizeof(buf));

...you're meant to specify a file descriptor for the read command read(2)

It turns out, you can pass in the file descriptor of "0" to read from standard input.

So you would simply do the following:

read(0, buf, sizeof(buf));

  • 1
    Yes!! That worked, thank you. I actually tried this before but it didn't work for me, I guess I just didn't compile my file lol. Anyways, thank you very much. – Pancakaeeeee Feb 15 '21 at 20:03
  • No problem...have a good day :) –  Feb 15 '21 at 20:05