Share this:


VARIATIONS IN DECLARING STRUCTURES
Consider the following,
struct date {
int month, day, year;
} todays_date, purchase_date;
or another way is,
struct date {
int month, day, year;
} todays_date = { 9,25,1985 };
or, how about an array of structures similar to date,
struct date {
int month, day, year;
} dates[100];
Declaring structures in this way, however, prevents you from using the structure definition later in the program. The structure definition is thus bound to the variable name which follows the right brace of the structures definition.
CLASS EXERCISE C22
Write a program to enter in five dates, Store this information in an array of structures.
CLASS EXERCISE C22
#include
struct date { /* Global definition of date */
int day, month, year;
};
main()
{
struct date dates[5];
int i;
for( i = 0; i < 5; ++i ) {
printf(“Please enter the date (dd:mm:yy)” );
scanf(“%d:%d:%d”, &dates[i].day, &dates[i].month,
&dates[i].year );
}
}
STRUCTURES WHICH CONTAIN STRUCTURES
Structures can also contain structures. Consider where both a date and time structure are combined into a single structure called date_time, eg,
struct date {
int month, day, year;
};
struct time {
int hours, mins, secs;
};
struct date_time {
struct date sdate;
struct time stime;
};
This declares a structure whose elements consist of two other previously declared structures. Initialization could be done as follows,
static struct date_time today = { { 2, 11, 1985 }, { 3, 3,33 } };
which sets the sdate element of the structure today to the eleventh of February, 1985. The stime element of the structure is initialized to three hours, three minutes, thirty-three seconds. Each item within the structure can be referenced if desired, eg,
++today.stime.secs;
if( today.stime.secs == 60 ) ++today.stime.mins;
BIT FIELDS
Consider the following data elements defined for a PABX telephone system.
flag = 1 bit
off_hook = 1 bit
status = 2 bits
In C, these can be defined as a structure, and the number of bits each occupy can be specified.
struct packed_struct {
unsigned int flag:1;
unsigned int off_hook:1;
unsigned int status:2;
} packed_struct1;
The :1 following the variable flag indicates that flag occupies a single bit. The C compiler will assign all the above fields into a single word.
Assignment is as follows,
packed_struct1.flag = 0;
packed_struct1.status = 3;
if( packed_struct1.flag )
………….

Practise Exercise 9: Structures

1. Define a structure called record which holds an integer called loop, a character array of 5 elements called word, and a float called sum.
2. Declare a structure variable called sample, defined from a structure of type record.
3. Assign the value 10 to the field loop of the sample structure of type record.
4. Print out (using printf) the value of the word array of the sample structure.
5. Define a new structure called birthdays, whose fields are a structure of type time called btime, and a structure of type date, called bdate.
Practice Exercise 9: Structures( Answers)
1. Define a structure called record which holds an integer called loop, a character array of 5 elements called word, and a float called sum.
struct record {
int loop;
char word[5];
float sum;
};
2. Declare a structure variable called sample, defined from a structure of type struct record.
struct record sample;
3. Assign the value 10 to the field loop of the sample structure of type struct record.
sample.loop = 10;
4. Print out (using printf) the value of the word array of the sample structure.
printf(“%s”, sample.word );
5. Define a new structure called birthdays, whose fields are a structure of type struct time called btime, and a structure of type struct date, called bdate.
struct birthdays {
struct time btime;
struct date bdate;
};
DATA CONVERSION
The following functions convert between data types.
atof() converts an ascii character array to a float
atoi() converts an ascii character array to an integer
itoa() converts an integer to a character array
Example
/* convert a string to an integer */
#include
#include
char string[] = “1234”;
main()
{
int sum;
sum = atoi( string );
printf(“Sum = %dn”, sum );
}
/* convert an integer to a string */
#include
#include
main()
{
int sum;
char buff[20];
printf(“Enter in an integer “);
scanf(” %d”, &sum );
printf( “As a string it is %sn”, itoa( sum, buff, 10 ) );
}
Note that itoa() takes three parameters,
  • the integer to b converted
  • a character buffer into which the resultant string is stored
  • a radix value (10=decimal,16=hexadecimal)
In addition, itoa() returns a pointer to the resultant string.
FILE INPUT/OUTPUT
To work with files, the library routines must be included into your programs. This is done by the statement,
#include
as the first statement of your program.
  • Associate the variable with a file using fopen()

    Before using the variable, it is associated with a specific file by using the fopen() function, which accepts the pathname for the file and the access mode (like reading or writing).
    in_file = fopen( “myfile.dat”, “r” )
    In this example, the file myfile.dat in the current directory is opened for read access.
    Process the data in the file

    Use the appropriate file routines to process the data
    When finished processing the file, close it

    Use the fclose() function to close the file.

    fclose( in_file );
USING FILES
  • Declare a variable of type FILE
    To use files in C programs, you must declare a file variable to use. This variable must be of type FILE, and be declared as a pointer type.
FILE is a predefined type. You declare a variable of this type as
FILE *in_file;
This declares infile to be a pointer to a file.

The following illustrates the fopen function, and adds testing to see if the file was opened successfully.
#include
/* declares pointers to an input file, and the fopen function */
FILE *input_file, *fopen ();
/* the pointer of the input file is assigned the value returned from the fopen call. */
/* fopen tries to open a file called datain for read only. Note that */
/* “w” = write, and “a” = append. */
input_file = fopen(“datain”, “r”);
/* The pointer is now checked. If the file was opened, it will point to the first */
/* character of the file. If not, it will contain a NULL or 0. */
if( input_file == NULL ) {
printf(“*** datain could not be opened.n”);
printf(“returning to dos.n”);
exit(1);
}
NOTE: Consider the following statement, which combines the opening of the file and its test to see if it was successfully opened into a single statement.
if(( input_file = fopen (“datain”, “r” )) == NULL ) {
printf(“*** datain could not be opened.n”);
printf(“returning to dos.n”);
exit(1);
}
INPUTTING/OUTPUTTING SINGLE CHARACTERS
Single characters may be read/written with files by use of the two functions, getc(), and putc().
int ch;
ch = getc( input_file ); /* assigns character to ch */
The getc() also returns the value EOF (end of file), so
while( (ch = getc( input_file )) != EOF )
………………….
NOTE that the putc/getc are similar to getchar/putchar except that arguments are supplied specifying the I/O device.
putc(‘n’, output_file ); /* writes a newline to output file */
CLOSING FILES
When the operations on a file are completed, it is closed before the program terminates. This allows the operating system to cleanup any resources or buffers associated with the file. The fclose() function is used to close the file and flush any buffers associated with the file.
fclose( input_file );
fclose( output_file );
COPYING A FILE
The following demonstrates copying one file to another using the functions we have just covered.
#include
main() /* FCOPY.C */
{
char in_name[25], out_name[25];
FILE *in_file, *out_file, *fopen ();
int c;
printf(“File to be copied:n”);
scanf(“%24s”, in_name);
printf(“Output filename:n”);
scanf(“%24s”, out_name);
in_file = fopen ( in_name, “r”);
if( in_file == NULL )
printf(“Cannot open %s for reading.n”, in_name);
else {
out_file = fopen (out_name, “w”);
if( out_file == NULL )
printf(“Can’t open %s for writing.n”,out_name);
else {
while( (c = getc( in_file)) != EOF )
putc (c, out_file);
putc (c, out_file); /* copy EOF */
printf(“File has been copied.n”);
fclose (out_file);
}
fclose (in_file);
}
}
TESTING FOR THE End Of File TERMINATOR (feof)
This is a built in function incorporated with the stdio.h routines. It returns 1 if the file pointer is at the end of the file.
if( feof ( input_file ))
printf(“Ran out of data.n”);
THE fprintf AND fscanf STATEMENTS
These perform the same function as printf and scanf, but work on files. Consider,

Practise Exercise 9A: File Handling


Practise Exercise 11: Pointers & Structures

Practice Exercise 11: Pointers & Structures (Answers)

Practice Exercise 11a: Pointers & Structures(Answers)


subscriber

Leave a Reply

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

Accept Our Privacy Terms.*