forked from sudikrt/assignments
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2_5_temp_file.c
60 lines (50 loc) · 1.75 KB
/
2_5_temp_file.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
/* A Handler for a temporary file created with write_temp_file.
In this implementation it's just a file descripter */
typedef int temp_file_handle;
/* Writes length bytes from BUFFER into a temporary file. The
temporary file is immediately unlinked. Returns a handle to the
temporary file */
temp_file_handle write_temp_file (char* buffer, size_t length)
{
/* Create the filename and file. The XXXXXX will be replaced with
characters that make the filename unique*/
char temp_filename[] = "/tmp/temp_file.XXXXXX";
int fd = mkstemp (temp_filename);
/* Unlink the file immediately, so that it will be removed when the
file descriptor is closed. */
//unlink (temp_filename);
/* Writes the number of bytes first. */
write (fd, &length, sizeof(length));
/* Now writing the data itself. */
write (fd, buffer, length);
return fd;
}
/* Reads the content of file a temporary file*/
char* read_temp_file (temp_file_handle temp_file, size_t* length)
{
char* buffer;
/* The TEMP_FILE handle is a file descriptor to the temporary file. */
int fd = temp_file;
/* Rewind to the beginning of the file. */
lseek (fd, 0, SEEK_SET);
/* Read the size of the data in the temporary file. */
read (fd, length, sizeof (*length));
/* Allocate a buffer and read the data. */
buffer = (char*) malloc (*length);
read (fd, buffer, *length);
/* Close the file descriptor, which will cause the temporary file to
go away. */
close (fd);
return buffer;
}
int main ()
{
char* buffer = "#include <stdlib.h>/* Write the number of bytes to the file";
size_t len = 100000000;
int i = write_temp_file (buffer, strlen(buffer));
printf ("Contents are :\n %s", read_temp_file (i, &len));
}