Debian Codegraph @

listings/chapter-2/readfile.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 <fcntl.h>
8 #include <stdlib.h>
9 #include <sys/stat.h>
10 #include <sys/types.h>
11 #include <unistd.h>
12
13 char* read_from_file (const char* filename, size_t length)
14 {
15 char* buffer;
16 int fd;
17 ssize_t bytes_read;
18
19 /* Allocate the buffer. */
20 buffer = (char*) malloc (length);
21 if (buffer == NULL)
22 return NULL;
23 /* Open the file. */
24 fd = open (filename, O_RDONLY);
25 if (fd == -1) {
26 /* open failed. Deallocate buffer before returning. */
27 free (buffer);
28 return NULL;
29 }
30 /* Read the data. */
31 bytes_read = read (fd, buffer, length);
32 if (bytes_read != length) {
33 /* read failed. Deallocate buffer and close fd before returning. */
34 free (buffer);
35 close (fd);
36 return NULL;
37 }
38 /* Everything's fine. Close the file and return the buffer. */
39 close (fd);
40 return buffer;
41 }