This is the function I use to load it, sometimes it works but when I leave the program and compile again, it will just crash:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//this is how I declared the list
struct plantillas {
int iduser;
int idplant;
char name[31];
int pres;
int punt;
struct plantillas *next;
};
struct plantillas *first, *last;
//This is the main that calls loadfile:
int main(){
FILE *file;
file = fopen("Plantillas.txt", "r");
puts("a");
load_file(file);
fclose(file);
}
//this is the funcion that actually loads the file
void load_file(FILE *file) {
char cadaux[100];
first = (struct plantillas *) NULL;
last = (struct plantillas *) NULL;
struct plantillas *new;
while (!feof(fichero)){
/* save memory for the new element on the list */
new = (struct plantillas *) malloc(sizeof(struct plantillas));
if (new == NULL) printf("No memory avaiable!\n");
fflush(stdout);
readline(file, cadaux); //I'll explain about this later
sscanf(cadaux, "%d %d %s %d %d", &new->iduser, &new->idplant, new->name, &new->pres, &new->punt);
new->next = NULL;
/* this will find out if the linked list is empty or not */
if (first == NULL) {
first = new;
last = new;
}
else {
/* if it isn't, the one that was last before now has to point to the next element on the list */
last->next = new;
/* now we make the new be the last */
last = new;
}
}
}
/*The readline function is because of format issues. As it is an assignment for school, the format of the file has to be in1-int2- string1-int3-int4, readline reads each line on the file and turn the '-' into ' ' and then saves it into an auxiliary string. Here is the function:*/
void readline(FILE * a, char * b)
{
int i;
fscanf(a, "%s", b);
for (i = 0; b[i] != '\n'; i++)
{
if (b[i] == '-') b[i] = ' ';
}
}
Sorry if there are some variables that doenst match at all, I translated the code from spanish to try make it more understandable. Also, sorry for the formating issues, its my first post here and I had some trouble