我正在实现自己的 Redis在 C 中,我通过分配足够的内存来保存 n
unsigned longs(比如单词)然后使用单词偏移量和位偏移量来设置/清除位置 pos< 的位来设计位图
word_offset = pos / BITS_PER_WORD;
bit_offset = pos % BITS_PER_WORD;
下一步是通过将位图写入磁盘来持久化该位图,可以再次读回以恢复位图。
作为第一个天真的方法,我尝试逐字读取内存并将这个 unsigned long 写入文件。它可以工作,但看起来很丑陋,工作缓慢并且感觉很笨,因为位图的大小可以增长到 512mb。
此外,我必须将多个这样的位图存储到一个文件中。
如何设计一种有效的方法将我的数据结构保存到磁盘。由于这是一个学习项目,我避免窥视 Redis 源代码。
最佳答案
参见 fwrite :
#include <stdio.h>
size_t fwrite(const void *restrict ptr, size_t size, size_t nitems,
FILE *restrict stream);
The
fwrite()
function shall write, from the array pointed to byptr
, up tonitems
elements whose size is specified by size, to the stream pointed to by stream. For each object, size calls shall be made to thefputc()
function, taking the values (in order) from an array of unsigned char exactly overlaying the object. The file-position indicator for the stream (if defined) shall be advanced by the number of bytes successfully written. If an error occurs, the resulting value of the file-position indicator for the stream is unspecified.
read对应的函数是fread .
如果 POSIX 是唯一的要求,请使用 write :
#include <unistd.h>
ssize_t pwrite(int fildes, const void *buf, size_t nbyte,
off_t offset);
ssize_t write(int fildes, const void *buf, size_t nbyte);
The
write()
function shall attempt to writenbyte
bytes from the buffer pointed to bybuf
to the file associated with the open file descriptor,fildes
.
read对应的函数是read .
关于C 向/从磁盘写入/读取内存快照,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38744378/