磁盘上的链接列表数组

时间:2010-10-17 01:58:46

标签: 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
 }
}
  1. 我相信通过使用fseek(),我可以指向文件中数组的特定元素/结构。但我无法理解所有以前的元素是否需要写入。
  2. 这可以通过磁盘上的动态分配来完成吗?
  3. 如何将元素链接到链接列表中的另一个元素? 任何一个例子肯定会有所帮助!

1 个答案:

答案 0 :(得分:3)

好吧,正如Amardeep所说,这听起来像是最好用某种数据库来完成的事情,比如,或者像Berkeley DB。但无论如何,让我们回答这些问题。

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

  2. 是否可以使用动态分配排序取决于文件系统。许多UNIX文件系统支持*稀疏*分配,这意味着如果分配块365,则不必分配块0到364.有些不行。

  3. 假设你有一个长度 k 的结构看起来或多或少是这样的:

  4. (欺骗解析)

    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);
    
相关问题