#include <stdlib.h>
#include <unistd.h>
/* A handle for a temporary file created with write_temp_file. In
this implementation, it’s just a file descr
iptor. */
/*write_temp_file是個操作臨時文件的句柄,本例中只是個文件描述符*/
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. */
/*在這函數從BUFFER中向臨時文件寫入LENGTH字節數據。臨時文件在剛一創建就被刪除掉。函數會返回臨時文件的句柄。*/
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. */
/*新建文件名和文件,文件名中的XXXXXX將被隨機字符串代替,以保證文件名在系統中的唯一性*/
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,這樣只要文件描述符一關閉文件就會被自動刪除*/
unlink (temp_filename);
/* Write the number of bytes to the file first. */
/*首先寫入即將寫入數據的長度*/
write (fd, &length, sizeof (length));
/* Now write the data itself. */
/*寫入數據本身*/
write (fd, buffer, length);
/* Use the file descriptor as the handle for the temporary file. */
/*函數返回文件描述符,作為臨時文件的句柄*/
return fd;
}
/* Reads the contents of a temporary file TEMP_FILE created with
write_temp_file. The return value is a newly allocated buffer of
those contents, which the caller must deallocate with free.
*LENGTH is set to the size of the contents, in bytes. The
temporary file is removed. */
/*從被write_temp_file創建的臨時文件中讀取數據。返回值是含有文件內容的新申請到的內存塊,這塊內存應該又調用read_temp_file者釋放。
*length是臨時文件正文內容的長度。執行完read_temp_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. */
/*fd是訪問臨時文件的文件描述符*/
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;
}