Hello everyone I have this code:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
struct ficha{
char dni[9];
char nombre[20];
char p_apellido[20];
char s_apellido[20];
char telefono[9];
};
ficha fichas[20]; //creamos array de tipo ficha de 20
ficha aux[20]; //creamos array auxiliar para almacenar datos
int main(){
FILE *fp; //creamos variable tipo file que se llama fp
fp=fopen("datos.txt", "r"); // abrimos en fp el archivo datos.txt con permiso de lectura (r)
if(fp == NULL){
perror("Error al abrir el archivo");
return(-1);
}
else{
char *ptr;
char *tmp;
for (int i =0; i<10; i++){//si hay mas de 10 elementos cambiar 10 por el numero que sea.
fscanf(fp,"%s",aux[i].dni); //almacenando datos de fichero en aux[i]
}
for (int i =0; i<10; i++){
tmp=aux[i].dni;
ptr = strtok(tmp,"; \n");
printf("PTR %i:%s \n",i,ptr);
strcpy(fichas[i].dni, ptr); //almacenando dni en fichas
printf("ficha %i : \n DNI: %s ",i,fichas[i].dni);
printf ("DNIBUENO: %s ", fichas[0].dni);
ptr = strtok(NULL,"; \n"); //te lo hace hasta NULL
printf ("DNIBUENO1: %s", fichas[0].dni);
printf("PTR %i:%s \n",i,ptr);
printf ("DNIBUENO2: %s", fichas[0].dni);
strcpy(fichas[i].nombre, ptr); //almacenando nombre
printf ("DNIBUENO3: %s", fichas[0].dni);
printf("Nombre: %s ",fichas[i].nombre);
printf("auxatope %i:%s \n",i,fichas[0].dni);
ptr = strtok(NULL,"; \n");
printf("PTR %i:%s \n",i,ptr);
strcpy(fichas[i].p_apellido, ptr); //apellido
printf("1 Apellido: %s ",fichas[i].p_apellido);
ptr = strtok(NULL,"; \n");
printf("PTR %i:%s \n",i,ptr);
strcpy(fichas[i].s_apellido, ptr); //2 apellido
printf("2 Apellido: %s ",fichas[i].s_apellido);
ptr = strtok(NULL,"; \n");
printf("PTR %i:%s \n",i,ptr);
strcpy(fichas[i].telefono, ptr); //telefono
printf("Telefono %s \n", fichas[i].telefono);
}
}
fclose(fp);
return 0;
}
I put a lot of printf to know what is the value variable in each moment.
My problems begins when I try to insert nombre (name) inside my struct array, the fichas[i].dni takes the name too and his value is 34567890DDIEGO when must be 34567890D.
I don't know if it's the strtok or the strcpy. Any help?
Thanks!