我试图找到如何在磁盘上存储和处理(搜索,添加,删除)链接列表数组。例如在内存中,它想
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
}
}
任何例子肯定会有所帮助!
最佳答案
好的,正如Amardeep所说,这听起来像是最好使用某种数据库(例如Berkeley DB)来完成的事情。但是还是让我们回答这些问题。
(欺骗解析)
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);
po记录513在内存中由
b
指向。获取以下记录lseek(file, (sizeof(struct blk)*b->next), SEEK_SET);