load file content into structure

PoorStudent
PoorStudent used Ask the Experts™
on
how do I read in a file into structure variables?
any help is greatly appreicate.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
What kind of file? What is the file format? Do you have any code thus far?

Commented:
Can u give the example of file content?
Commented:
Is it a text file or binary file?
If you are using a structure to write to the file (The contents will be binary in this case), then the same structure can be used to read from the file.
Otherwise, you have to have a standard format for your text file and all the records have to follow the same format. I will explain the way it is to be done by taking a simple example. Say, you are using a text file and each record contains an integer id, a name (string of characters), address (string of characters) and salary (floating point number).
Then your structure definition will look like this:
struct record {
   int id;
   char name[25];
   char addr[25];
   float salary;
} rec1;

Now you can use fopen() to open the file [FILE *fp; fp = fopen("data.txt", "r");].
fread() to read the contents of the file to structure [fread((struct record *) &rec1, sizeof(rec1), 1, fp); ]
fclose() to close the file [fclose(fp);]

If you have many records, then keep fread() in a while loop and do it until you get EOF.

Hope this solves your problem.

-Narendra
Top Expert 2006

Commented:
No comment has been added lately and this question is therefore classified abandoned.

If asker wishes to close the question, then refer to
http://www.experts-exchange.com/help/closing.jsp

Otherwise, I will leave a recommendation in the Cleanup topic area that this question is:
PAQed with A grade to ssnkumar

Please leave any comments here within the next seven days. It is assumed that any participant not responding to this request is no longer interested in its final disposition.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

Sunny
EE Cleanup Volunteer

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial