0

If you are trying to use the function read() in C, and you want to read from the terminal, what should you write????

1 Answers1

-1

I posted this question, because there wasn't a clear and simple answer anywhere. Use: char buffer[10]; read(0, buffer, 10)

Where there is a 0, you have 3 options: 0 - for stdin 1 - for stdout 2 - for stderr

Shame on you :/

  • You shouldn't hardcode "magic" numbers. It is better practice to use the symbolic names `STDIN_FILENO`, `STDOUT_FILENO`, and `STDERR_FILENO`. – SGeorgiades Feb 23 '22 at 02:04
  • Also, "10" is a sort of a magic number too.... better to use `sizeof buffer`. – SGeorgiades Feb 23 '22 at 02:06
  • Even though 0 has been documented since about 1970 in a series of books that has sold more copies than *any* other computer science book, using a macro makes searching code a *whole* lot easier. Ask yourself "what would I search for to find all places where I'm reading from stdin and not see any false positives?" Additionally, stdin will never be changed from 0. Too many programs would break. – Jeff Holt Feb 23 '22 at 02:08
  • *Every* number other than `-1`, `0`, and `1` should probably be done as a symbolic constant. Just out of interest, if you saw the value `1440` in source code, what would you think it was? I have three possibilities. – paxdiablo Feb 23 '22 at 02:13
  • 2
    shame on who? .. – M.M Feb 23 '22 at 02:35
  • Those "symbolic names" are defines, so if you write 0, 1, or 2 instead is the same thing. And you should avoid, as a good IT, using sizeof whatever. – Sofia Leite Feb 23 '22 at 19:57
  • @paxdiablo: [wikipedia](https://en.wikipedia.org/wiki/1000_(number)#1400_to_1499) says `1440` is "the number of minutes in one day, the blocksize of a standard 3 1/2 floppy disk, and the horizontal resolution of WXGA(II) computer displays" -- I could only think of *something time-related* :) – pmg Feb 23 '22 at 20:05
  • @png, I didn't have the screen resolution one. good find. I instead had twips per inch. – paxdiablo Feb 23 '22 at 21:32
  • @SofiaLeite, you're correct that `const int` would be better than `#define` since the latter is unlikely to be visible to the debugger. However, even defines are better then magic numbers since they both make the intent clear and make it easy to change something (in one place) without interfering with a different magic number that just happens to have the same value. With `60` peppered throughout your code, how do you know whether they're secs/min, mins/hr, seating capacity, max devices per device manager, and so on. A human may easily be able to figure it out but search/replace will not. – paxdiablo Feb 23 '22 at 21:38