linux c消息临时存储,在linux下使用c语言操作临时文件

#include /* A handle for a temporary file created with write_temp_file. In

this implementation, it’s just a file descriptor. */

/*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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值