Guys,
I'm trying to read the content from a text file that goes is with this format:
First Line: last account created
Other Lines: Account number \t holdersName \t personalCode \t money
Well, in order to do it, I got this structure where I want to insert the data so I can use for other functions of it:
Code:
typedef struct ContaFicheiro {
unsigned int numero;
char nomeUtilizador[19];
char PIN[4];
float saldo;
} ContaFicheiro;
And the function that reads from this file is this one:
Code:
void leAccounts() {
FILE *fp;
int i = 0;
int k;
char linha[80];
unsigned int ultimaContaCriada = 0;
char *item;
if( (fp = fopen("accounts.txt", "r")) != NULL) {
fscanf(fp, "%u\n", &ultimaContaCriada);
//DEBUG
printf("\nUltima conta criada: %u\n", ultimaContaCriada);
while(fgets(linha, sizeof linha, fp) != NULL) {
//DEBUG
printf("\nLinha %d: %s\n", i, linha);
printf("Antes de fazer o tokenizer... \n");
item = strtok(linha, "\t");
contas[i].numero = atoi(item);
printf("Finalizado o primeiro tokenizer.\n");
item = strtok(NULL, "\t");
strcpy(contas[i].nomeUtilizador, item);
item = strtok(NULL, "\t");
strcpy(contas[i].nomeUtilizador, item);
printf("Finalizado o segundo tokenizer.\n");
item = strtok(NULL, "\t");
strcpy(contas[i].PIN, item);
printf("Finalizado o terceiro tokenizer.\n");
item = strtok(NULL, "\t");
contas[i].saldo = atoi(item);
printf("Finalizado ultimo tokenizer.\n");
printf("\nConta %d: \nNumero: %u \t Nome: %s \t PIN: %s \t Saldo: %f \t \n", i, contas[i].numero,
contas[i].nomeUtilizador,
contas[i].PIN,
contas[i].saldo);
i++;
}
//DEBUG
/*
for(k = 0; k < i; k++) {
printf("Numero: %u\tNome: %s\t PIN: %s\t Saldo: %f\n", contas[k].numero,
contas[k].nomeUtilizador,
contas[k].PIN,
contas[k].saldo);
}*/
}
The problem is that, when I run it it gives me the "Segmentation Fault" error and I think it's because of the strtok or strcpy function, but I don't have any idea on how to correct it.
Can you help me with this?
P.S.: Don't pay that much attention to the printfs in the middle of the while cycle, it was purely to understand if the program was getting there before the "segmentation fault" error...