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
}
}
好的,正如Amardeep所说,这听起来像是最好使用某种数据库来完成的事情,比如,或者说,Berkeley DB。但我们还是要回答问题
// 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);