Search code examples
cposix

C read() function difficulty understanding file descriptor


I'm having difficulity understanding the read function in C.

len = read(fd, buf, 32);

when I assign fd as 0,1,2 and run the program, its basically doing the same thing, can someone tell me what difference does this make?


Solution

  • As far as I understand your question it is why nothing changes if you read from file descriptors 0, 1, 2.

    In a normal program the file descriptor 0 is stdin, 1 is stdout and 2 is stderr. stdin is where you should read your input, 1 is where you should write your output and 2 is where you should write your error messages.

    It is not uncommon that all three file descriptors may point to the same underlying file (a file can also be the console, network connection, etc.) behind the scenes. If you're just running your program from the command line this is actually quite likely. In that case you may be able to read from all of them and get the exact same result.

    But. Then you decide that you want to save the output of the program in a file and run it like this: program > output. Now file descriptor 1 is no longer pointing to the same file as stdin and your program would break. Same thing happens if you point stderr to some error logging facility. Or get the input from a file or a pipe. Or run the program in some debuggers. Or a different terminal. This is why you should only read from 0 and no other file descriptors, even if you might get away with it sometimes.