I have a txt file that looks like this: (str)name (str)last_name (int)weight (int)height
and I'm supposed to save it in a linked list. Everything seems to work, up until I print the list and it's all empty or 0 values. I did something very similiar that used a scanf()
function and worked, this is why I think the problem might be related to fscanf()
function instead.
Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#define ERR -1
#define OK 0
#define MAX 50
struct profile {
char name[MAX];
char lname[MAX];
int weight;
int height;
struct profile* next;
};
void print_profiles(struct profile** head) {
struct profile* curr = *head;
while (curr != NULL) {
printf("%s %s\t%d %d\n", curr->name, curr->lname, curr->weight, curr->height);
curr = curr->next;
}
putchar('\n');
}
int readSize(FILE *fp) {
int lines = 0;
for (char c=getc(fp); c!=EOF; c=getc(fp))
if (c == '\n') lines++;
return lines;
}
int readFile(char *file, struct profile** head) {
FILE *fp = fopen(file, "r");
if (fp == NULL) return ERR;
int lines = readSize(fp);
struct profile *curr, *prev;
curr = prev = NULL;
for (int i=0; i<lines; i++) {
curr = malloc(sizeof(struct profile));
fscanf(fp, "%s%s%d%d", curr->name, curr->lname, &curr->weight, &curr->height);
curr->next = NULL;
if (i == 0) *head = curr;
else prev->next = curr;
prev = curr;
}
fclose(fp);
return OK;
}
void freeNode(struct profile** head) {
struct profile* curr = *head;
while (curr != NULL) {
struct profile* next = curr->next;
free(curr);
curr = next;
}
head = NULL;
}
int main() {
struct profile* head = NULL;
readFile("profiles.txt", &head);
print_profiles(&head);
freeNode(&head);
return 0;
}