I am developing a database-like application that stores a a structure containing:
struct Dictionary
{
char *key;
char *value;
struct Dictionary *next;
};
As you can see, I am using a linked list to store information. But the problem begins when the user exits out of the program. I want the information to be stored somewhere. So I was thinking of storing the linked list in a permanent or temporary file using fopen, then, when the user starts the program, retrieve the linked list. Here is the method that prints the linked list to the console:
void PrintList()
{
int count = 0;
struct Dictionary *current;
current = head;
if (current == NULL)
{
printf("\nThe list is empty!");
return;
}
printf(" Key \t Value\n");
printf(" ======== \t ========\n");
while (current != NULL)
{
count++;
printf("%d. %s \t %s\n", count, current->key, current->value);
current = current->next;
}
}
So I am thinking of modifying this method to print the information through fprintf instead of printf and then the program would just get the infomation from the file. Could someone help me on how I can read and write to this file? What kind of file should it be, temporary or regular? How should I format the file (like I was thinking of just having the key first, then the value, then a newline character)?
The file should probably be regular. A temp file isn't guaranteed to be there the next time your start your application. Also, your format there looks fine for humans, not so fine for machines. I'd recommend either creating your own binary file format or using XML(or maybe JSON?). You could probably format it pretty easily like
key1\0value1\0key2\0value2\0....
I'll write a quick example is psuedoish code:
//To write...
Dictionary *this=begin_list;
while(this!=null){
for(i=0;i<strlen(this->key);i++){
write_byte(this->key[i]);
}
for(i=0;i<strlen(this->value);i++){
write_byte(this->value[i]);
}
this=this->next;
}
//to read...
Dictionary *prev;
Dictionary *this;
char *buffer;
while(!eof){
buffer=malloc(MAX_STRING_LEN);
int i=0;
this=malloc(sizeof(Dictionary)
while(i<MAX_STRING_LEN){ //note no error checking
buffer[i]=read_byte();
if(buffer[i]==0){
break;
}
}
this->key=buffer;
buffer=malloc(MAX_STRING_LEN)
while(i<MAX_STRING_LEN){ //note no error checking
buffer[i]=read_byte();
if(buffer[i]==0){
break;
}
}
this->value=buffer;
if(prev!=null){
prev->next=this;
}
this->next=null;
prev=this;
}
I know it's a poor example. I think scanf or similar may make the job a ton easier, but my C skills are getting rusty.