Jo.
Jo.

Reputation: 9

C File Save and Restore input information

I have a program based on a struct with different information. In this program you can for example add people and delete people etc. I already have all this done, so the program it self is done. But the files are not.

So I am trying to write a code that "saves" if I would for example add a person and this would "save" when I choose to exit the program. And a code that "restores" the people in the file in the beginning of the program.

Does any one have any ideas or tips? I'm new to programming and trying to learn. I have been sitting with this for a few days. Before I "restore" I ask for an file to open and if this file does not exist a new one is created and this works. So if I would have a file with 3 employees and I would open this file I would want to restore them and then being able to add more employees to the file etc.

Upvotes: 0

Views: 662

Answers (2)

Matthias
Matthias

Reputation: 8180

You have to write (and to read) in two steps: first the struct, and then the array the struct points to. Code fragment for writing (a.o. without error checking, that is however needed):

#include <stdio.h>
// ...
employees emp;
const char* filename="your_filename";
// populate emp;
FILE* file = fopen(filename,"w");
fwrite(&emp,sizeof(employees),1,file);
fwrite(emp.pic,sizeof(int),emp.imageCount,file);
fclose(file);

Now you have the array after the struct in your file. Read it in the same way:

FILE* file = fopen(filename,"r");
fread(&emp,sizeof(employees),1,file);
emp.pic=calloc(sizeof(int), emp.imageCount); 
fread(emp.pic,sizeof(int),emp.imageCount,file);

Please don't forget to check for errors (see man fopen|fread|fwrite|calloc). In case you have several structs, you must repeat the two steps for any element.

Upvotes: 1

i486
i486

Reputation: 6563

What is the platform? For Windows there is simple format of .INI files with contents like:

[Employee_1]
id=123
name=Smith
imageCount=2
...

You can use GetPrivateProfileString/GetPrivateProfileInt and WritePrivateProfileString API functions to read and store the information. Use separate section for each employee. One common section is necessary to store the number of employee sections.

Upvotes: 0

Related Questions