C 磁盘上的链表数组

C 磁盘上的链表数组,c,linked-list,hashtable,fseek,C,Linked List,Hashtable,Fseek,我试图找到如何在磁盘上存储和处理(搜索、添加、删除)一组链表。例如在内存中,它会 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 } } 我相信通过使用fseek()可以指向文件中数组的特定

我试图找到如何在磁盘上存储和处理(搜索、添加、删除)一组链表。例如在内存中,它会

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
 }
}
  • 我相信通过使用fseek()可以指向文件中数组的特定元素/结构。但我无法理解之前的所有元素是否都需要编写
  • 这可以通过磁盘上的动态分配来实现吗
  • 如何将该元素链接到链接列表中的另一个元素? 任何例子都会有帮助
    好的,正如Amardeep所说,这听起来像是最好使用某种数据库来完成的事情,比如,或者说,Berkeley DB。但我们还是要回答问题

  • 您确实可以使用fseek(或其系统调用lseek)来确定磁盘上的位置,并在以后找到它。如果使用某种计算偏移量的方法,则实现了我们过去称之为直接文件的内容;否则,您可能会存储一个索引,这将引导您使用索引顺序方法

  • 是否可以通过动态分配来完成这一点取决于文件系统。许多UNIX文件系统支持*稀疏*分配,这意味着如果分配块365,则不必分配块0到364。有些人没有

  • 假设有一个长度为k的结构,大致如下所示:

  • (欺骗解析)

    创建第一个项目;将其块编号设置为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);
    

    听起来您正试图以艰难的方式重新创建数据库管理器的功能。为什么不揭示一下您正试图用这种方法解决的核心问题呢?我正在用C代码搜索一个文件,生成散列并将它们存储在散列数组中。为了避免冲突,我创建了一个链表数组。它在内存中工作得很好,但它对我可以存储的哈希数有限制。因此,唯一可能的方法是将它们存储在HDD中。是否有一种DB方法可以有效解决此问题?
    lseek(file, (sizeof(struct blk)*b->next), SEEK_SET);