Structure
Structure is a user-defined data type that enables us to store the collection of different data types
at different memory locations. Each element of a structure is called a member. The struct keyword
is used to define the structure.
The syntax to define the structure is:
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type member N;
};
The example to define a structure for an entity employee is:
struct employee
{ int id;
char name[20];
float salary;
};
The following image shows the memory allocation of the structure employee that is defined in the
above example.
Here, struct is the keyword; employee is the name of the structure; id, name, and salary are the
members or fields of the structure.
Declaring structure variable
We can declare a variable for the structure so that we can access the member of the structure easily.
There are two ways to declare structure variable:
1. By struct keyword within main() function
2. By declaring a variable at the time of defining the structure.
1st way:
To declare the structure variable by struct keyword. It should be declared within the main function.
struct employee
{ int id;
char name[50];
float salary;
};
Now write given code inside the main() function.
struct employee e1, e2;
The variables e1 and e2 can be used to access the values stored in the structure.
.
2nd way:
Another way to declare variable at the time of defining the structure.
struct employee
{ int id;
char name[50];
float salary;
}e1,e2;
Accessing members of the structure
There are two ways to access structure members:
1. By . (member or dot operator)
2. By -> (structure pointer operator)
Structure example
#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
}e1; //declaring e1 variable for structure
void main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "Ram");//copying string into char array
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
getch();
}
Output:
employee 1 id : 101
employee 1 name : Ram
Union
Union can be defined as a user-defined data type which is a collection of different variables of
different data types in the same memory location. The union can also be defined as many members,
but only one member can contain a value at a particular point in time.
Union is a user-defined data type, but unlike structures, they share the same memory location.
Defining a Union
To define a union, you must use the union statement in the same way as you did while defining a
structure. The union statement defines a new data type with more than one member for your
program.
The format of the union statement is as follows −
union {
member definition;
member definition;
...
member definition;
} [one or more union variables];
At the end of the union's definition, before the final semicolon, you can specify one or more union
variables but it is optional. Here is the way you would define a union type named Data having
three members i, f, and str −
union Data {
int i;
float f;
char str[20];
} data;
Accessing Union Members
To access any member of a union, we use the member access operator (.). The
member access operator is coded as a period between the union variable name and the
union member that we wish to access. You would use the keyword union to define
variables of union type. The following example shows how to use unions in a program −
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
void main( ) {
union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
strcpy( data.str, "C Programming");
printf( "data.str : %s\n", data.str);
getch();
}
When the above code is compiled and executed, it produces the following result −
data.i : 10
data.f : 220.500000
data.str : C Programming
Here, all the members are getting printed very well because one member is being used at a time.
Difference between Structure and Union
Struct Union
The struct keyword is used to define a structure. The union keyword is used to define union.
When the variables are declared in a structure, the compiler When the variable is declared in the union, the compiler
allocates memory to each variable member. The size of a allocates memory to the largest size variable member. The
structure is equal or greater to the sum of the sizes of each data size of a union is equal to the size of its largest data member
member. size.
Each variable member occupied a unique memory space. Variables members share the memory space of the largest
size variable.
Changing the value of a member will not affect other variables Changing the value of one member will also affect other
members. variables members.
Each variable member will be assessed at a time. Only one variable member will be assessed at a time.
We can initialize multiple variables of a In union, only the first data member can be initialized.
structure at a time.
All variable members store some value at any point in the Exactly onlyonedatamember stores avalue at any particular
program. instance in the program.
The structure allows initializing multiple Union allows initializing only one variable member at
variable members atonce. once.
It is used to store different data type values. It is used for storing one at a time from different data
typevalues.
It allows accessing and retrieving any data member at a time. It allows accessing and retrieving any one data member
at a time.
File Handling in C
File Handling is the storing of data in a file using a program. In C programming language, the programs
store results, and other data of the program to a file using file handling in C.
File handling in C enables us to create, update, read, and delete the files stored on the local file
system through our C program.
The following operations can be performed on a file.
o Creation of the new file
o Opening an existing file
o Reading from the file
o Writing to the file
o Deleting the file
Functions for file handling
There are many functions in the C library to open, read, write, search and close the file.
A list of file functions are given below:
No. Function Description
1 fopen() opens new or existing file
2 fprintf() write data into the file
3 fscanf() reads data from the file
4 fputc() writes a character into the file
5 fgetc() reads a character from file
6 fclose() closes the file
7 fseek() sets the file pointer to given position
8 fputw() writes an integer to file
9 fgetw() reads an integer from file
10 ftell() returns current position
11 rewind() sets the file pointer to the beginning of the file
Opening File: fopen()
We must open a file before it can be read, write, or update. The fopen() function is used to
open a file. The syntax of the fopen() is given below:
FILE *fopen( const char * filename, const char * mode );
The fopen() function accepts two parameters:
The file name (string). If the file is stored at some specific location, then we must mention the path
at which the file is stored. For example, a file name can be like "c://some_folder/some_file.ext".
The mode in which the file is to be opened. It is a string.
We can use one of the following modes in the fopen() function.
Mode Description
r opens a text file in read mode
w opens a text file in write mode
a opens a text file in append mode
r+ opens a text file in read and write mode
w+ opens a text file in read and write mode
a+ opens a text file in read and write mode
rb opens a binary file in read mode
wb opens a binary file in write mode
ab opens a binary file in append mode
The fopen function works in the following way.
o Firstly, It searches the file to be opened.
o Then, it loads the file from the disk and place it into the buffer. The buffer is
used to provide efficiency for the read operations.
o It sets up a character pointer which points to the first character of the file.
Consider the following example which opens a file in write mode.
#include<stdio.h>
void main( )
{
FILE *fp ;
char ch ;
fp = fopen("file_handle.c","r") ;
while ( 1 )
{
ch = fgetc ( fp ) ;
if ( ch == EOF )
break ;
printf("%c",ch) ;
}
fclose (fp ) ;
}
Closing File: fclose()
The fclose() function is used to close a file. The file must be closed after performing all the
operations on it. The syntax of fclose() function is given below:
int fclose( FILE *fp );
Writing File : fprintf() function
The fprintf() function is used to write set of characters into file. It sends formatted output to a stream.
Syntax:
int fprintf(FILE *stream, const char *format [, argument, ...])
Example:
#include <stdio.h>
main(){
FILE *fp;
fp = fopen("file.txt", "w");//opening file
fprintf(fp, "Hello file by fprintf...\n");//writing data into file
fclose(fp);//closing file
}
Reading File : fscanf() function
The fscanf() function is used to read set of characters from file. It reads a word from the
file and returns EOF at the end of file.
Syntax:
int fscanf(FILE *stream, const char *format [, argument, ...])
Example:
#include <stdio.h>
void main(){
FILE *fp;
char buff[255];//creating char array to store data of file
fp = fopen("file.txt", "r");
while(fscanf(fp, "%s", buff)!=EOF){
printf("%s ", buff );
}
fclose(fp);
}