0

The signatures for read / write are below:

 ssize_t write(int fd, const void *buf, size_t count);

 ssize_t read(int fd, void *buf, size_t count);

Why doesn't read() also take a const void *? Does that mean it changes the value of buf?

  • 4
    What matters is that it changes the values that `buf` points to. This makes sense: it is going to replace the contents of the buffer with the data read from the file. `write`, on the other hand, doesn't need to change the buffer contents at all. – Nate Eldredge Jan 29 '21 at 01:52
  • 1
    `read` writes the output into the space pointed to by `buf` – M.M Jan 29 '21 at 01:53
  • https://stackoverflow.com/questions/1143262/what-is-the-difference-between-const-int-const-int-const-and-int-const/1143272#1143272 – Retired Ninja Jan 29 '21 at 01:53
  • Thanks! I mistook the meaning of ```const``` – Max Darling Jan 29 '21 at 02:29
  • @Max Darling Re "*I mistook the meaning of `const`*", `void * const buf` would mean `buf` itself can't be changed. And of course, `const void * const buf` can't change `buf` or that to which it points. /// Keep in mind that changing `buf` itself in the function has no effect on the caller because C always passes by value. So there's not much point in making parameters constant (but there's lots of value in making constant the buffer itself). – ikegami Jan 29 '21 at 05:43

1 Answers1

1

Because write() won't change the contents of the buffer, but only write it to the file.

On the other hand, read() will change its buffer (from what's in the file) so it had better not be const.

General rule, what changes isn't const.

Joshua
  • 40,822
  • 8
  • 72
  • 132