0

So I have tried looking for something similar to my situation but I cant find anything that helps or that is simple enough for me to understand.

My issue I am sure is not difficult, but I do not know how to do the following:

I have a structure within a structure and need to scan in multiple files into the main structure. This is what I have and the point where I am stuck is in messages. I feel as though I may need one more structure, but again I am not sure

these are my structures

 typedef struct {
int year;
int month;
int day;
char time[9];
 } datetime_t

 typedef struct
 {
datetime_t datetime;
double latitude;
double longitude;
double magnitude;
double depth;
char location[LOCATION]
 } data_t

here is my scanning file

  void scan_data(data_t Alaska[], data_t Central[],data_t Inner[],
 data_t East[],data_t West[],data_t Canada[MAX_INFO])
 {
int i=0; 
FILE *FAlaska;
FILE *FCentral;
FILE *FInner;
FILE *FEast;
FILE *FWest;
FILE *FCanada;

FAlaska = fopen("Alaska.txt", "r");
FCentral = fopen("Central.txt", "r");
FInner = fopen("InnerMountain.txt", "r");
FEast = fopen("NorthEast.txt", "r");
FWest = fopen("NorthWest.txt", "r");
FCanada = fopen("NorthernCanada.txt", "r");

while  (i < MAX_DATA && 
    fscanf(FAlaska, "%s", data[i].datetime) !=EOF) /*here is my issue*/
{                                                      
    fscanf(FAlaska, "d", data.latitude);
}
fclose(FAlaska);
return;
  }

I am not sure how or if I can scan data into a structure within a structure? Do you do data[I].datetime.year? or scan into datetime as a separate array/struct and then assign it later to the bigger struct?

any help would be much appreciated on how to do this. Thank You.

puzzlekid
  • 11
  • 3
  • You ask [`fscanf`](http://en.cppreference.com/w/c/io/fscanf) to read a string, and write it to a structure, you can't do that. First of all, when `scanf` (and family) reads a string it reads a *space delimited* string, so if the string you want to read contains spaces it will not read all. Secondly, you need to read each field of the nested structure separately, if it's in the file that way. – Some programmer dude Dec 07 '14 at 01:13
  • Perhaps http://stackoverflow.com/questions/2722606/how-to-parse-a-string-into-a-datetime-struct-in-c or http://stackoverflow.com/questions/12071342/reading-a-date-with-sscanf will be of some help. Duplicates? – Jim Mischel Dec 07 '14 at 04:21
  • @JoachimPileborg I see your point, Ill work on this. – puzzlekid Dec 07 '14 at 07:02

1 Answers1

0

I am not sure how or if I can scan data into a structure within a structure? Do you do data[I].datetime.year?

Yes, we do. For example, if your date/time format is "YYYY-MM-DD hh:mm:ss", you can use

data = Alaska;
…
    fscanf(FAlaska, "%d-%d-%d %8s", &data[i].datetime.year,
                                    &data[i].datetime.month,
                                    &data[i].datetime.day, data[i].datetime.time) …
Armali
  • 18,255
  • 14
  • 57
  • 171