Example:
Code:
#include <stdio.h>
#include <string.h>
#define DATA_FILE "data~.txt"
struct DataRec
{
char Name[31];
unsigned int Age;
};
static void WriteData();
static void ReadData();
int main(int argc, char* argv[])
{
/* CREATE SOME TEST DATA */
WriteData();
/* READ THE TEST DATA BACK FROM THE FILE */
ReadData();
return 0;
}
static void
WriteData()
{
FILE *fp;
struct DataRec MyRec;
if ((fp = fopen(DATA_FILE, "w")) != NULL)
{
strcpy(MyRec.Name, "John Public");
MyRec.Age = 25;
fwrite(&MyRec, sizeof(MyRec), 1, fp);
strcpy(MyRec.Name, "Mike Miller");
MyRec.Age = 30;
fwrite(&MyRec, sizeof(MyRec), 1, fp);
fclose(fp);
}
}
static void
ReadData()
{
FILE *fp;
struct DataRec Rec1;
struct DataRec Rec2;
if ((fp = fopen(DATA_FILE, "r")) != NULL)
{
/* read the first structure but don't display it */
fread(&Rec1, sizeof(DataRec), 1, fp);
/* read the second structure and display it */
fread(&Rec2, sizeof(DataRec), 1, fp);
printf("Name: %s Age: %d\n", Rec1.Name, Rec1.Age);
printf("Name: %s Age: %d\n", Rec2.Name, Rec2.Age);
if (Rec1.Age == Rec2.Age)
printf("Ages are the same\n");
else
printf("Ages are different\n");
fclose(fp);
}
}