Debian Codegraph @

listings/appendix-b/write-all.c

raw
1 /***********************************************************************
2 * Code listing from "Advanced Linux Programming," by CodeSourcery LLC *
3 * Copyright (C) 2001 by New Riders Publishing *
4 * See COPYRIGHT for license information. *
5 ***********************************************************************/
6
7 #include <assert.h>
8 #include <unistd.h>
9
10 /* Write all of COUNT bytes from BUFFER to file descriptor FD.
11 Returns -1 on error, or the number of bytes written. */
12
13 ssize_t write_all (int fd, const void* buffer, size_t count)
14 {
15 size_t left_to_write = count;
16 while (left_to_write > 0) {
17 size_t written = write (fd, buffer, count);
18 if (written == -1)
19 /* An error occurred; bail. */
20 return -1;
21 else
22 /* Keep count of how much more we need to write. */
23 left_to_write -= written;
24 }
25 /* We should have written no more than COUNT bytes! */
26 assert (left_to_write == 0);
27 /* The number of bytes written is exactly COUNT. */
28 return count;
29 }