You may well be lucky that I can't sleep tonight.
I'm too buggered to provide an overview or description. My efforts in crafting the code carefully are likely to be similarly short-changed..
You should use the debugger to step through the code and a hex-editor to review the created data-file. You'll notice I use (modified) pascal-style strings in the data file since it simplifies loading.
#include <stdio.h>
#include <string.h>
typedef struct node
{
char *text;
int num;
node *next;
};
void addNode(node* &listHead,char *newText, int newInt)
{
node *curPos;
curPos = listHead;
if (curPos == NULL)
{
listHead = new node;
curPos = listHead;
}
else
{
while (curPos->next != NULL)
curPos = curPos->next;
curPos->next = new node;
curPos = curPos->next;
}
curPos->next = NULL;
curPos->num = newInt;
curPos->text = strdup(newText);
}
void dispList(node *firstNode)
{
node *curNode;
curNode = firstNode;
while (curNode != NULL)
{
printf("Text: %s\n", curNode->text);
printf("Num: %d\n", curNode->num);
curNode = curNode->next;
if (curNode)
printf("\n");
}
}
void saveListToFile(node *firstNode, char *szFilename)
{
node *curNode;
FILE *fp;
char asciiNull = 0;
int sLen;
curNode = firstNode;
fp = fopen(szFilename, "wb");
while (curNode != NULL)
{
sLen = strlen(curNode->text);
fwrite(&sLen, sizeof(int), 1, fp);
fwrite(curNode->text, 1, sLen, fp);
fwrite(&curNode->num, sizeof(curNode->num), 1, fp);
curNode = curNode->next;
}
fclose(fp);
}
node *loadListFromFile(char *szFilename)
{
FILE *fp;
node *result = NULL;
char strBuffer[32];
int intBuffer, sLen;
char tmpChar;
fp = fopen(szFilename, "rb");
printf("filePos: %d\n", ftell(fp));
fread(&sLen, sizeof(int), 1, fp);
strBuffer[sLen] = 0;
fread(strBuffer, 1, sLen, fp);
fread(&intBuffer, sizeof(int), 1, fp);
addNode(result, strBuffer, intBuffer);
while (!feof(fp))
{
fread(&sLen, sizeof(int), 1, fp);
strBuffer[sLen] = 0;
fread(strBuffer, 1, sLen, fp);
fread(&intBuffer, sizeof(int), 1, fp);
addNode(result, strBuffer, intBuffer);
}
fclose(fp);
return result;
}
int main()
{
char buffer[32];
int i;
node *listHead, *loadedList;
listHead = NULL;
for (i=0; i<10; i++)
{
sprintf(buffer, "item_%d", i+1);
addNode(listHead, buffer, i+1);
}
saveListToFile(listHead, "list.dat");
loadedList = loadListFromFile("list.dat");
printf("Created list:\n");
dispList(listHead);
printf("Loaded list:\n");
dispList(loadedList);
return 0;
}
|