Debian Codegraph @

listings/appendix-b/read-file.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 <stdio.h>
9 #include <stdlib.h>
10 #include <sys/stat.h>
11 #include <sys/types.h>
12 #include <unistd.h>
13
14 /* Read the contents of FILENAME into a newly-allocated buffer. The
15 size of the buffer is stored in *LENGTH. Returns the buffer, which
16 the caller must free. If FILENAME doesn't correspond to a regular
17 file, returns NULL. */
18
19 char* read_file (const char* filename, size_t* length)
20 {
21 int fd;
22 struct stat file_info;
23 char* buffer;
24
25 /* Open the file. */
26 fd = open (filename, O_RDONLY);
27
28 /* Get information about the file. */
29 fstat (fd, &file_info);
30 *length = file_info.st_size;
31 /* Make sure the file is an ordinary file. */
32 if (!S_ISREG (file_info.st_mode)) {
33 /* It's not, so give up. */
34 close (fd);
35 return NULL;
36 }
37
38 /* Allocate a buffer large enough to hold the file's contents. */
39 buffer = (char*) malloc (*length);
40 /* Read the file into the buffer. */
41 read (fd, buffer, *length);
42
43 /* Finish up. */
44 close (fd);
45 return buffer;
46 }