HolyGraal
HolyGraal

Reputation: 13

How to control the output of fileno?

I'm facing a piece of code that I don't understand:

read(fileno(stdin),&i,1);
switch(i)
{
    case '\n':
      printf("\a");
      break;
    ....

I know that fileno return the file descriptor associated with the sdtin here, then read put this value in i variable.

So, what should be the value of stdin to allow i to match with the first "case", i.e \n ?

Thank you

Upvotes: 0

Views: 1324

Answers (2)

John Bollinger
John Bollinger

Reputation: 181034

I know that fileno return the file descriptor associated with the sdtin here,

Yes, though I suspect you don't know what that means.

then read put this value in i variable.

No. No no no no no. read() does not put the value of the file descriptor, or any part of it, into the provided buffer (in your case, the bytes of i). As its name suggests, read() attempts to read from the file represented by the file descriptor passed as its first argument. The bytes read, if any, are stored in the provided buffer.

stdin represents the program's standard input. If you run the program from an interactive shell, that will correspond to your keyboard. The program attempts to read user input, and to compare it with a newline.

The program is likely flawed, and maybe outright wrong, though it's impossible to tell from just the fragment presented. If i is a variable of type int then its representation is larger than one byte, but you're only reading one byte into it. That will replace only one byte of the representation, with results depending on C implementation and the data read.

What the program seems to be trying to do can be made to work with read(), but I would recommend using getchar() instead:

#include <stdio.h>

/*
...
int i;
...
*/

i = getchar();

/* ... */

Upvotes: 0

P.P
P.P

Reputation: 121407

But what should be the value of stdin to match with the first "case", i.e \n ?

The case statement doesn't look at the "value" of stdin.

 read(fileno(stdin),&i,1);

reads in a single byte into i (assuming read() call is successful) and if that byte is \n (newline character) then it'll match the case. You probably need to read the man page of read(2) to understand what it does.

Upvotes: 2

Related Questions