Read/Write linked lists from/to file
Hi, I'm trying to make a simple database, where I write a linked list to a file and then read it out again.
I've been working on this for the last week and I've been stuck most of the time hehe :D But anywho, this is the code;
Code:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#define TRUE 1
void newname(void);
void listfromfile(void);
struct medlem
{
char name[255];
char medlem[255];
struct medlem *ptrnext;
};
struct medlem *ptrfirst = NULL;
void main(void)
{
char ch;
while(TRUE)
{
printf("\nTryk 'e' for at indtast medlem\n");
printf("\nTryk 'p' for at laese fra fil\n");
printf("\nTryk 'q' for at quitte ;>\n");
ch = getche();
switch(ch)
{
case 'e':
newname(); break;
case 'p':
listfromfile(); break;
case 'q':
printf("\n");
exit(1);
default:
printf("\nForkert valg. \n");
}
}
}
void newname(void)
{
FILE *fp;
struct medlem *ptrthis;
struct medlem *ptrfirst;
ptrthis = malloc(sizeof(struct medlem));
ptrfirst = malloc(sizeof(struct medlem));
if(ptrthis == NULL)
{
printf("Allocation failed.\n");
return;
}
ptrthis->ptrnext = ptrfirst;
if( (fp = fopen("c:\\database.txt", "a")) == NULL)
{
printf("\nCan't open file\n");
exit(1);
}
printf("\nEnter name: ");
gets(ptrthis->name);
printf("\nEnter number: ");
gets(ptrthis->medlem);
//write to file
fwrite(ptrthis, sizeof(*ptrthis), 1, fp);
fclose(fp);
}
void listfromfile(void)
{
struct medlem *ptrthis;
FILE *fp;
ptrthis = malloc(sizeof(struct medlem));
ptrfirst = ptrthis;
if( (fp = fopen("c:\\database.txt", "r")) == NULL)
{
printf("No such file\n");
exit(1);
}
if(ptrthis == NULL)
{
printf("NULL\n");
exit(1);
}
while(fread(ptrthis, sizeof(*ptrthis), 1, fp) ==1)
{
printf("\nNavn: %s\n", ptrthis->name);
printf("\nNumber: %s\n", ptrthis->medlem);
ptrthis = ptrthis->ptrnext;
}
}
Nothing happens really.. Something gets written to the file, but it aint' clear text :| And when I call the "listfromfile" function, nothing happens.
Where did I fail? :)