Debian Codegraph @

listings/chapter-2/temp_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 <stdlib.h>
8 #include <unistd.h>
9
10 /* A handle for a temporary file created with write_temp_file. In
11 this implementation, it's just a file descriptor. */
12 typedef int temp_file_handle;
13
14 /* Writes LENGTH bytes from BUFFER into a temporary file. The
15 temporary file is immediately unlinked. Returns a handle to the
16 temporary file. */
17
18 temp_file_handle write_temp_file (char* buffer, size_t length)
19 {
20 /* Create the filename and file. The XXXXXX will be replaced with
21 characters that make the filename unique. */
22 char temp_filename[] = "/tmp/temp_file.XXXXXX";
23 int fd = mkstemp (temp_filename);
24 /* Unlink the file immediately, so that it will be removed when the
25 file descriptor is closed. */
26 unlink (temp_filename);
27 /* Write the number of bytes to the file first. */
28 write (fd, &length, sizeof (length));
29 /* Now write the data itself. */
30 write (fd, buffer, length);
31 /* Use the file descriptor as the handle for the temporary file. */
32 return fd;
33 }
34
35 /* Reads the contents of a temporary file TEMP_FILE created with
36 write_temp_file. The return value is a newly-allocated buffer of
37 those contents, which the caller must deallocate with free.
38 *LENGTH is set to the size of the contents, in bytes. The
39 temporary file is removed. */
40
41 char* read_temp_file (temp_file_handle temp_file, size_t* length)
42 {
43 char* buffer;
44 /* The TEMP_FILE handle is a file descriptor to the temporary file. */
45 int fd = temp_file;
46 /* Rewind to the beginning of the file. */
47 lseek (fd, 0, SEEK_SET);
48 /* Read the size of the data in the temporary file. */
49 read (fd, length, sizeof (*length));
50 /* Allocate a buffer and read the data. */
51 buffer = (char*) malloc (*length);
52 read (fd, buffer, *length);
53 /* Close the file descriptor, which will cause the temporary file to
54 go away. */
55 close (fd);
56 return buffer;
57 }