C 向/从磁盘写入/读取内存快照

标签 c memory-management file-io redis

我正在实现自己的 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 by ptr, up to nitems elements whose size is specified by size, to the stream pointed to by stream. For each object, size calls shall be made to the fputc() 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 write nbyte bytes from the buffer pointed to by buf to the file associated with the open file descriptor, fildes.

read对应的函数是read .

关于C 向/从磁盘写入/读取内存快照,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38744378/

相关文章:

c++ - 在 C++ Win32 应用程序中,我如何确定私有(private)字节、工作集和虚拟大小

c++ - 优化文件读写

java - 为什么我会收到 InputMismatchException?

c++ - 提供相对文件路径

c - 为什么传递给库的函数指针(作为回调)在执行时不会导致段错误?

c - 如何在函数中打印 void * 以及如何在函数中访问 void * 变量?

memory-management - 如何在现有的 Haskell 代码中从 String 转到 Data.ByteString.Lazy?

c++ - Codeblocks 中的图形程序

c - 使用 strtok [C] 时获取 Null 值

C++,无法使用数组或 vector ,如何使用指针来解决这个问题?