How do I use structures in C Programming

/*
* Program to use structures
* From the book: C Programming Visual Quickstart Guide
*
* One structure at a time is written to a binary file
*/

#include <stdio.h>

/*
* Set the file path and name as a C preprocessor macro.
*/

#define THEFILE "weather.dat"

int main (void) {

/*
* Define a structure and create a variable of that type.
* The structure will be called weather_record. It contains
* three members: a character array called date, an integer
* called high, and another integer called low. Each of 
* these correspond to the variables that were used in the
* previous versions of this application. 
* One variable of the weather_record type is created, 
* called today. Note that you have to use both the 
* keyword struct as well as the structure name in
* defining this variable.
*/

struct weather_record {
/*
* YYYY-MM-DD
*/
char date[11];

int high;
int low;

};

/* 
* One structure variable of type weather_record.
*/

struct weather_record today;

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

FILE *fp;

/* 
* Attempt to open the file for appended binary writing.
*/

fp = fopen(THEFILE, "ab");

/*
* The file is open.
*/
if (fp != NULL) {

/*
* Prompt the user.
*/

printf("Enter a date, the high tempature, and the low tempature.\n(YYYY-MM-DD ## ##): ");

/* 
* Handle the input, assigning it to the structure fields.
*/

if(scanf ("%10s %d %d", today.date, &today.high, &today.low) ==3) {

/*
* Write the data.
*/

fwrite(&today, sizeof(struct weather_record), 1, fp);
printf("The data has been written.\n");

} else {

printf("The data was not in proper format.\n");
}

} 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 could not be closed.\n");
}

/*
* Pause
*/
getchar();
getchar();
return 0;

} 

Leave a Reply

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