【问题标题】:Array of Linked lists on disk磁盘上的链表数组
【发布时间】:2011-04-26 11:38:14
【问题描述】:

我正在尝试查找如何在磁盘上存储和处理(搜索、添加、删除)链表数组。例如在内存中,它会喜欢

struct list {
 int a;
 struct list *next;
}LIST

LIST *array[ARRAY_SIZE]

int main{
...
 LIST *foo = array[pointer];
 /* Search */
 while(foo!=NULL){
   ...
   foo=foo->next
 }
}
  1. 我相信通过使用 fseek() 可以指向文件中数组的特定元素/结构。但是我无法理解是否需要编写所有先前的元素。
  2. 这可以通过磁盘上的动态分配来完成吗?
  3. 如何将元素链接到链接列表中的另一个元素? 任何例子肯定会有所帮助!

【问题讨论】:

  • 听起来您正试图以艰难的方式重新创建数据库管理器的功能。你为什么不揭示你试图用这种方法解决的核心问题?
  • 我正在通过 C 代码搜索文件,生成哈希并将它们存储在哈希数组中。为了避免冲突,我创建了一个链表数组。它在内存中运行良好,但它对我可以存储的哈希数量有限制。因此,唯一可能的方法是将它们存储在 HDD 中。有没有一种数据库方法可以有效解决这个问题?

标签: c linked-list hashtable fseek


【解决方案1】:

好的,正如 Amardeep 所说,这听起来像是在实践中最好使用某种数据库(如 Berkeley DB)来完成的事情。但无论如何,让我们回答问题吧。

  1. 您确实可以使用 fseek(或其系统调用,lseek)来确定磁盘上的某个位置并稍后找到它。如果您使用某种计算偏移量的方法,那么您就是在实现我们以前称为 direct 文件的内容;否则你可能会存储一个索引,这会将你引向索引顺序方法。

  2. 是否可以通过动态分配来完成取决于文件系统。许多 UNIX 文件系统支持 *sparse* 分配,这意味着如果分配块 365,则不必分配块 0 到 364。有些则不需要。

  3. 假设您有一个长度为 k 的结构,看起来或多或少像这样:

(欺骗解析)

struct blk { 
    // some stuff declared here
    long next;  // the block number of the next item
};

您创建了第一个项目;将其块号设置为 0。设置在某个可区分值旁边,例如 -1。

// Warning, this is off the cuff code, not compiled.
struct blk * b = malloc(sizeof(struct blk));
// also, you should really consider the case where malloc returns null.

// do some stuff with it, including setting the block next to 1.
lseek(file, 0, SEEK_SET);  // set the pointer at the front of the file
write(file, sizeof(struct blk), b);  // write it.
free(b);

// make a new block item
malloc(sizeof(struct blk));
// Do some stuff with it, and set next to 2.
lseek(file, 0, SEEK_CUR);  // leave the pointer where it was, end of item 0
write(file, sizeof(struct blk), b);  // write it.
free(b);

您现在在磁盘上有两个项目。保持这一点,您最终将在磁盘上拥有一千个项目。现在,要找到第 513 项,您只需

lseek(file, (sizeof(struct blk)*513), SEEK_SET);

你需要一个缓冲区;既然我们释放了以前的那些,我们会再做一个

b = malloc(sizeof(struck blk);

读取那么多字节

read(file, sizeof(struct blk), b);

并且 poof 记录 513 位于 b 指向的内存中。获取以下记录

lseek(file, (sizeof(struct blk)*b->next), SEEK_SET);

【讨论】:

    猜你喜欢
    • 2018-10-26
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 2011-04-28
    • 2020-02-06
    相关资源
    最近更新 更多