Search code examples
cfile-descriptor

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


Solution

  • 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();
    
    /* ... */