Mar 30, 2009 at 1:36pm UTC
Well if anyone can point out what I'm doing wrong. Output seems fine but the input crashes on me. As it's not reading the file correctly.
1
1.000000
1
1.000000
1
1.000000
1
1.000000
1
1.000000
1
1.000000
1
1.000000
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
void SaveListToFile(Node **pStart, Node **pCurrent)
{
FILE *pFile = fopen("linkedlist.txt" , "w" );
while ( (*pStart)->next != NULL )
{
//Save To File Here
fprintf(pFile, "%d\n" , (*pStart)->age);
fprintf(pFile, "%f\n" , (*pStart)->height);
*pStart = (*pStart)->next;
}
fclose(pFile);
}
void OpenListFromFile(Node **pStart, Node **pCurrent)
{
FILE *pFile = fopen("linkedlist.txt" , "r" );
if ( pFile != NULL )
{
while ( !feof(pFile) )
{
fscanf(pFile, "%d\n%f\n" , &(*pStart)->age, &(*pStart)->height);
*pStart = (*pStart)->next;
}
}
fclose(pFile);
}
pCurrent isn't used at the moment. Just trying to figure out what I'm doing wrong while reading the file.
Cheers,
Myth.
Last edited on Mar 30, 2009 at 2:28pm UTC
Mar 30, 2009 at 1:52pm UTC
SaveListToFile
is fine.
OpenListFromFile
should create a new node, read the data from the file into it and add it to the front or back of the list.
You're reading data from the file into the same note each time and (re)setting the next ponter to the head node. You end up with a list with a single node that points to itself as the next node. The should cause SaveListToFile
to drop into an infinite loop displaying the last entry of the file.
Mar 30, 2009 at 1:57pm UTC
Any idea on how exactly I should change it so I'm not infinite looping. As I feel that this could be done without a temporary variable.
Thanks kbw
It's reading the file like this though as well
+ pFile 0x695e1448 {_ptr=0x007934a9 "
1.111111
2
2.222222
3
3.333333
4
4.444444
5
5.555555
6
6.666666
7
7.777777
7
7.777777
ÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ _ _iobuf *
So It's taking 7 and 7.77777 twice and I gather Í is for some form of non-initialized variable. Hmmm?
The saving file was wrong. Just fixed it by doing this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
void SaveListToFile(Node **pStart, Node **pCurrent)
{
FILE *pFile = fopen("linkedlist.txt" , "w" );
while ( *pStart != NULL )
{
//Save To File Here
fprintf(pFile, "%d\n" , (*pStart)->age);
fprintf(pFile, "%f\n" , (*pStart)->height);
*pCurrent = *pStart;
*pStart = (*pStart)->next;
}
fclose(pFile);
}
Was looking at the next Node pointer within the struct when I should of been looking at the struct itself
Last edited on Mar 30, 2009 at 2:18pm UTC
Mar 30, 2009 at 2:52pm UTC
That'll do.
You could maintain a pointer to the end of the list (the last node added), and that would save you from walking down to the end each time, giving constant time insertion rather than O(n) insertion.