MODULE 5
Structures, unions & files
Introduction: ( structure)
◦ A structure is a user defined data type that can stored related information (even of di erent data types).
◦ It is similar to records and can be used to store information about an entity.
◦ The major di erence between structure and an array is that array contains related information of the same
data type
◦ structure therefore is a collection of variables of di erent data types under a single name.
◦ The variables within a structure are of di erent data types and each has a name that is used to select it
from the structure.
Structure declaration:
◦ A structure is defined by the keyword struct followed by the structure name.
struct student
{
int usn;
char name[20];
char course[20];
float fees;
};
◦ In the above example usn, name, course, fees are the members of structure student
◦ Structure is a user defined data type.
◦ Size of structure is the addition of all size of all members. It will be equal to sum of all members or more.
◦ Each variable name declared within a structure is called a member of the structure.
◦ The structure declaration, however does not allocate any memory or consume storage space. It just gives a
template that conveys to C compiler how the structure could be laid out in the memory and give details of the
member names.
◦ Memory will be allotted only after we create a variable of type structure
◦ Structures can be local or global.
creating variable of structure data type:
struct student stud1;
struct student
{
int usn;
char name[20];
char course[20];
float fees;
} stud1, stud2;
struct student
{
int usn;
char name[20];
char course[20]; or struct student stud1= ={01,Rahul”, “BCA”, 45,000};
float fees;
} stud1={01,Rahul”, “BCA”, 45,000};
Array of structures:
typedef declaration:
◦ typedef keyword enables the programmer to create a new data type name from an existing data type.
◦ By using typedef no new data is created rather an alternate name(alias) is given to a known data type.
typedef int INTEGER
INTEGER num=5;
student stud1;
Accessing the members of the structure:
◦ A structure member variable is generally accessed through the dot(.) operator.
struct student stud1;
scanf(“%d”,&[Link]);
scanf(“%s”,&[Link]);
printf(“%d”, [Link]);
Copying structures:
struct student stud1={01,”Rahul”,”BCA”,45000};
stud2=stud1; //stud2 should be a variable of type student.
Comparing structures:
◦ C does not permit comparison of one structure to another. but, individual variables can be compared.
if([Link] > [Link]) valid statement.
Nested structure :
struct student stud1;
To read roll_no:
scanf(“%d”,&stud1.roll_no);
To read DOB:
scanf(“%d %d %d”, &[Link], &[Link], &[Link]);
Unions:
◦ Similar to structures, a union is a collection of variables of di erent data types
◦ the only di erence between structure and union is that in case of unions you can only store information in one
field at anyone time.
Unions inside structure:
Enumerated data type:
◦ Enumerated data type is a user defined type that consists of named integer constants.
◦ Each integer value is assigned an identifier.
◦ The identifier can be used as a symbolic name to make the program more readable. enum is the keyword.
enum COLORS { red, blue, black, green, yellow, purple, white}; COLORS is the new data type ( red till white
are called enumerators)
enum COLORS bg_color; / variable also can be created.
bg_color=black;
In the above example red=0, blue=1, black =2 and so on…
enum COLORS { red=2, blue, black=5, green=7, yellow, purple, white};
enum COLORS { red, blue, black, green, yellow, purple, white};
enum COLORS bg_color;
bg_color= black;
---------------------------------------------------------------------------------------------------------------
--------------------------------------
Files:
◦ File is a collection of data (relevant information) stored on a secondary storage device like hard
disk.
◦ When there is a huge amount of data taking the input from the computer's keyboard will be a
tedious job.
◦ A better solution therefore is to combine all input data into file and then design a C program to
read this data from the file whenever required.
Reasons for reading from files:
1. It becomes cumbersome and time consuming to handle huge amount of data through
terminals
2. when doing input output using terminal the entire data is lost when the program is
terminated, or computer is turned o .
Standard streams in C
stdin
stdout
Using Files in C:
To use files in C, we must follow the steps even below:
1. declare file pointer variable
2. open the file
3. process to file
4. close the file
Declaring the file pointer variable:
◦ we must specify the name of the file that has to be used this is accomplished by using a file pointer
variable what points to a structure FILE.
FILE *file_pointer_name;
FILE *fp;
The fp is the file pointer.
Opening a file: fopen()
◦ A file must be first opened before data can be read from it or written to it.
◦ In order to open a file and associate with the stream, the fopen() function is used.
FILE *fopen(const char *file_name, const char *mode);
◦ A pointer to structure is returned if it is successful
◦ if it fails it returns null.
◦ fp holds the address of the FILE object.
fopen() might fail in the following cases:
◦ Opening a file that is not ready for use.
◦ opening the file that is specified to be on non-existent directory or drive.(path)
◦ opening a non existent file for reading.
◦ opening a file to which access is not permitted.
Closing a file using fclose()
int fclose( FILE *fp);
◦ All the bu er or unprocessed input will be flushed
◦ fclose(fp);
◦ fcloseall(); / closes all file pointers opened
Reading data from files:
◦ fscanf()
fscanf(FILE *stream, const char *format, …);
fgets()
char *fgets( char *str,int size, FILE *stream);
◦ Reads at most one less than the number of characters specified by size from the given stream and stores in
the string str.
◦ The function terminates as soon as it encounters either a Character or EOF or any other error.
Writing data to files :
1. fprintf()
int fprint(FILE *stream, const char *format,…);
Example:
fp=fopen(“[Link]”, w);
….
fprintf(fp, “%d Name: %s, Salary: %f”, i, name, salary);
2. fputs() – used to write a line to a file
int fputs(const char *str, FILE *stream);
Example:
char feedback[100];
fp=fopen(“[Link]”, w);
…
gets(feedback); // input to feedback.
fputs(feedback, fp); //the given input feedback will be written to [Link]
Detecting End Of file:
◦ When reading or writing data to files we often don't know exactly how long the file is.
◦ In C there are 2 ways to detect the end of file.
1. While reading the file in text mode character by character the program can compare the character that has
been read with EOF, which is symbolic constant defined in stdio.h with the value of -1.
[Link] way is to use standard library function feof() which is defined in stdio.h. This function takes a pointer to
the file structure to check as an argument and returns zero when the end of file has not reached and a one if
end of file is reached.
int feof(FILE *fp);
feof(fp);