¿Utilizando fgets () y strtok () para leer un archivo línea por línea en C?
Estoy tratando de usar fgets y strtok () para leer un archivo línea por línea, y crear una lista enlazada de cada línea diferente de información.
En este momento, solo estoy poniendo la información en una matriz, solo para tratar de averiguar cómo leer la información correctamente, pero no está funcionando bien.
En la parte while (fgets), parece que carga todo en la matriz correctamente y lo imprime. Sin embargo, después de que se haya ejecutado ese bucle y trato de imprimir toda la matriz, obtengo resultados realmente extraños ... que son principalmente partes de la última línea SOLAMENTE, y no palabras completas ni nada en su mayor parte.
Por ejemplo, si estoy leyendo en:
Simpson, Homer, Male, 1976
Simpson, Marge, Female, 1978
Simpson, Bart, Male, 2002
Simpson, Lisa, Female, 2004
Simpson, Maggie, Female, 2011
La impresión que obtengo al final es algo como:
le
Simpson
Maggie
Simpson
Maggie
e
ale
Simpson
Maggie
e
e
Simpson
Maggie
Female
2011
Por favor, hágame saber a dónde me voy mal, gracias!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSTRINGSIZE 10
#define LINESIZE 128
struct person{
char firstName[MAXSTRINGSIZE];
char lastName[MAXSTRINGSIZE];
char gender[MAXSTRINGSIZE];
int birthYear;
struct person *next;
} *first, *current;
int main (void){
static const char filename[] = "Assignment1file.txt";
FILE *myfile = fopen ( "Assignment1file.txt", "r" );
int i=0;
int j=0;
int k=0;
int l=0;
char *result[10][4];
char line[LINESIZE];
char *value;
for(i=0; i<9; i++){
for(j=0;j<4;j++){
result[i][j] = NULL;
}
}
i=0;
// loop through each entry in Assignment1file
while(fgets(line, sizeof(line), myfile)){
//load last name
value = strtok(line, ",");
result[i][0] = value;
printf("%i 0 %s", i, value);
//load first time
value = strtok(NULL, ",");
result[i][1] = value;
printf("%i 1 %s", i, value);
// load gender
value = strtok(NULL, ",");
result[i][2] = value;
printf("%i 2 %s", i, value);
// load birth year
value = strtok(NULL, "\n");
result[i][3] = value;
printf("%i 3 %s", i, value);
printf("\n");
for(j=0;j<4;j++){
printf("%s\n", result[i][j]);
}
//go to next line
i++;
}
// read out the array
for(k=0; k<5; k++){
for(j=0;j<4;j++){
printf("%s\n", result[k][j]);
}
}
fclose(myfile);
return 0;
}