I have a function, which has to read a file, each line into a linked list element, but it can't read the content of the file.
The function is the following:
Leaderboard *Read()
{
FILE *fp = fopen("leaderboard.txt", "rt");
if (fp != NULL)
{
Leaderboard *head = malloc(sizeof(Leaderboard));
head->name = malloc(sizeof(char) * 21);
head->points = 0;
if (fscanf(fp, "%s %d\n", head->name, &head->points) == 2)
{
head->prev = NULL;
head->next = NULL;
Leaderboard *p = head;
while (!feof(fp))
{
Leaderboard *newElement = malloc(sizeof(Leaderboard));
newElement->name = malloc(sizeof(char) * 21);
newElement->points = 0;
fscanf(fp, "%s %d\n", newElement->name, &newElement->points);
{
newElement->next = NULL;
newElement->prev = p;
p->next = newElement;
p = p->next;
}
}
fclose(fp);
return head;
}
else
{
perror("An error occured while reading the file.");
fclose(fp);
free(head->name);
free(head);
return NULL;
}
}
else
{
perror("An error occured while opening the file.");
}
return NULL;
}
The file looks like this:
name point[int]
name2 point2[int]
...
For example
Peter 5
John 3
Bill 1
etc.
But when I try to read the file, it ruins the whole content, and I get ugly things like this:
đYgŚĹU 0
(I get this when I don't check the value of fscanf)
What is wrong with it?
UPDATE:
This is the function, which writes the new data into the file:
void Save(Uint16 *name, int point)
{
char* cname = UintToChar(name);
FILE *fp = fopen("leaderboard.txt", "wt");
if (fp == NULL)
{
perror("An error occured while opening the file.");
free(cnev);
return;
}
Leaderboard *head;
head = Read();
if (head == NULL)
{
fprintf(fp, "%s %d\n", cname, point);
free(cname);
fclose(fp);
return;
}
Leaderboard *new = malloc(sizeof(Leaderboard));
Leaderboard *p;
new->name = cname;
new->point = point;
if (head->next == NULL)
{
new->next = NULL;
new->prev = head;
head->next = new;
}
else
{
p = head;
while (p->next != NULL && p->points > point)
{
p = p->next;
}
if (p->points > point)
{
new->prev = p;
new->next = p->next;
p->next = new;
}
else
{
new->prev = p->prev;
p->prev->next = new;
new->next = p;
p->prev = new;
}
}
p = head;
int i = 1;
while (head != NULL && i <= 10)
{
fprintf(fp, "%s %d\n", head->name, head->points);
p = head->next;
free(head->name);
free(head);
head = p;
i++;
}
free(cname);
fclose(fp);
}