Hi,
well what I'm trying to do with this, is to read a text file line by line and pass its data to the struct. the problem is that not only i can't read the strings and put it on the struct fields, I also get a segmentation fault.
Could someone give me a little "light" here?
thanks!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGHT 78
typedef struct
{
char id_num[5];
char space;
char Name[50];
char Departure[10];
char Arrival[10];
char Day[2];
} PASSENGER;
void open_file() {
FILE *fp;
char s[20];
char s2[]="reservations.txt";
fprintf(stdout,"Write the text file name: ");
fgets(s,20,stdin);
if (!(strcmp(s,s2)==0)) {
s[strlen(s)-1]='\0';
fp=fopen(s,"r");
if (fp==NULL) {
fprintf(stderr,"Impossible to open the file %s\n\n",s);
exit(1);
}
else
fprintf(stdout,"File opened\n\n");
/* read lines from the file and save it on str */
char str[MAX_LENGHT];
PASSENGER p[6];
int i;
while ((fgets(str,MAX_LENGHT,fp))!=NULL) {
fprintf(stdout,"%s",str); /* shows every line in the text file */
for (i=0;i<6;++i) {
fscanf(fp,"%s%c%s%s%s%s",p[i].id_num,&p[i]space,p[i].Name,p[i].Departure,p[i].Arrival,p[i].Day); /* Should read the fields from the file */
printf("%s%c%s%s%s%s",p[i].id_num,p[i]space,p[i].Name,p[i].Departure,p[i].Arrival,p[i].Day); /* should show the fields from file /*
}
}
}
}
/* the text file is like this:
34012 Philip Morris Lisbon Milan 01
21092 John Peter Smith Paris Amsterdam 03
32467 Ann Mary Baptist Madrid Frankfurt 21
45201 Marian Silver Budapest Roma 02
42506 Michaelangelo Marks Berlin New York 30
12345 Bob Wilson Stuttgart Copenhagen07
*/
,