How to use typedef in C Programming

/* 
* Program to use typedef
* From the book: C Programming Visual Quickstart Guide
*
* The typedef operator can help shorten how you
* refer to structures. This application uses 
* those structures to read data from a binary 
* file.
*/

#include <stdio.h>

/*
* Set the file path and name.
*/

#define THEFILE "weather.dat"

int main(void) {

/* 
* Define the structure.
*/

struct weather_record {
char date[11];
int high;
int low;
};

/* 
* Use typedef to create an alias.
* The first line  makes an alias so that 
wr (short for weather_record) stands for 
struct weather_record. Then wr is used to
* create a day variable of type struct
weather_record.
*/

typedef struct weather_record wr;

/*
* Create a structure variable.
*/

wr day;

/*
* Need a pointer of type FILE.
*/

FILE *fp;

/* 
* Attempt to open the file for binary reading.
*/

fp = fopen(THEFILE, "rb");

/*
* The file is open.
*/

if (fp != NULL) {

/*
* Loop through the entire file, assigning each structure to day.
*/

while(fread(&day, sizeof(wr), 1, fp)) {

/* 
* Print the information using the structure's field.
*/

printf("Date: %s\nHigh: %d\nLow: %d\n\n", day.date, day.high, day.low);

}

} else {

printf("The file could not be opened.\n");

/*
* Exit the function/application.
*/

return 1;
}

/*
* Close the file
*/

if (fclose(fp) !=0) {
printf("The file cound not be closed.\n");
}

/*
* Pause
*/

getchar();
return 0;

}

Leave a Reply

Your email address will not be published. Required fields are marked *