By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,389 Members | 1,881 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,389 IT Pros & Developers. It's quick & easy.

Linked List and file reading

P: 1
Hello, I have been having a problem lately relating to a linked list example I wanted to try. For some reason, perhaps I am not saving the data to the linked list correctly OR my print function is incorrect. The two arguements to be passed are a filename and an integer (which I havent used yet). (I removed the freeLists section to save on posting space.)

To note, in the file a sample of data which would be used to read would be:
111 aaa bbb 1.1
222 ccc ddd 2.2

Which gives me an output of (which should really repeat exactly what is in the file):
=DX
=DX

----------------------code--------------------------
struct dataNodule
{
char* dataA;
char* dataB;
char* dataC;
char* dataD;

struct dataNodule *next;
};
typedef struct dataNodule dataNode;

void loadList(dataNode **startList, char* filename);
void printList(dataNode *startList, char* sortMethod);
void freeList(dataNode **startList);
dataNode* createNode(char* dataA, char* dataB, char* dataC, char* dataD);

int main(int argc, char *argv[])
{
dataNode *startPtr = NULL;

char *filename = 0, *sortMethod = 0;

if(argv[1] != NULL && argv[2] != NULL)
{
filename = argv[1];
sortMethod = argv[2];
}
else
{
exit(0);
}

loadList(&startPtr, filename);
printList(startPtr, sortMethod);

return 0;
}

void loadList(dataNode **startList, char* filename)
{
FILE *fin;
char dataA[10];
char dataB[30];
char dataC[30];
char dataD[10];
dataNode *tempPtr, *tailPtr = *startList;

fin = fopen(filename, "r");
if(fin == NULL)
{
printf("Can't open %s\n", filename);
exit(0);
}

while(fscanf(fin, "%s %s %s %s",
dataA, dataB, dataC, dataD) != EOF)
{
tempPtr = createNode(dataA, dataB, dataC, dataD);
if(tailPtr == NULL)
{
*startList = tailPtr = tempPtr;
}
else
{
tailPtr->next = tempPtr;
tailPtr = tempPtr;
}
}
}

dataNode* createNode(char* dataA, char* dataB, char* dataC, char* dataD)
{
dataNode *tempPtr;

tempPtr = (dataNode*) malloc(sizeof(dataNode));
if(tempPtr == NULL)
{
printf("Memory allocation error\n");
exit(0);
}
tempPtr->dataA = dataA;
tempPtr->dataB = dataB;
tempPtr->dataC = dataC;
tempPtr->dataD = dataD;
tempPtr->next = NULL;

return tempPtr;
}

void printList(dataNode *startList, char* sortMethod)
{
while(startList != NULL)
{
printf("%-7s %-20s %-20s %-7s\n",
startList->dataA, startList->dataB, startList->dataC, startList->dataD);
startList = startList->next;
}
}
--------------endofcode------------------
Nov 7 '06 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.