some user February 2016

Why write() returns ssize_t but takes a parameter of size_t?

I got a warning when compiling my code that calls write()

warning: comparison between signed and unsigned integer expressions [-Wsign-compare]

Here is the definition of write():

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

RETURN VALUE
   On success, the number of bytes written is returned  (zero  indicates
   nothing  was  written).   On  error, -1 is returned, and errno is set
   appropriately.

This just looks strange to me. Suppose ssize_t is int and I ended up writing something big (> 2GB). I can't just use a comparison of the returned value of write() vs count, can I?

(Edit: maybe I should write my question properly: What would be the right way to use write() without getting warning nor running into a situation that count == -1 after sign conversion? Yes, I know it is undefined behavior)

Answers


R Sahu February 2016

The return value is a signed type to allows the return value of -1 to indicate failure.

From http://linux.die.net/man/2/write:

On success, the number of bytes written is returned (zero indicates nothing was written). On error, -1 is returned, and errno is set appropriately.

Post Status

Asked in February 2016
Viewed 1,038 times
Voted 11
Answered 1 times

Search




Leave an answer