3

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

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. 如何将元素链接到链接列表中的另一个元素?任何例子肯定会有所帮助!
4

1 回答 1

4

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

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

  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);
于 2010-10-17T02:38:35.330 回答