UNIT-V: Structures in C and File Management:
STRUCTURES
The structure in C is a user-defined data type that can be used to group items of possibly different types into a single
type. The struct keyword is used to define the structure in the C programming language. The items in the structure
are called its member and they can be of any valid data type. Additionally, the values of a structure are stored in
contiguous memory locations.
C Structure Declaration
Syntax
struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
};
C Structure Definition
1. Structure Variable Declaration with Structure Template
struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
}variable1, varaible2, ...;
2. Structure Variable Declaration after Structure Template
// structure declared beforehand
struct structure_name variable1, variable2, .......;
Access Structure Members
We can access structure members by using the ( . ) dot operator.
Syntax
structure_name.member1;
strcuture_name.member2;
Initialize Structure Members
Structure members cannot be initialized with the declaration. For example, the following C program fails in the
compilation.
Default Initialization
By default, structure members are not automatically initialized to 0 or NULL. Uninitialized structure members will
contain garbage values. However, when a structure variable is declared with an initializer, all members not
explicitly initialized are zero-initialized.
struct Point
{
int x;
int y;
};
struct Point p = {0}; // Both x and y are initialized to 0
We can initialize structure members in 3 ways which are as follows:
1. Using Assignment Operator.
struct structure_name str;
str.member1 = value1;
str.member2 = value2;
str.member3 = value3;
.
.
.
2. Using Initializer List.
struct structure_name str = { value1, value2, value3 };
3. Using Designated Initializer List.
struct structure_name str = { .member1 = value1, .member2 =
value2, .member3 = value3 };
Array of Structures
An array whose elements are of type structure is called array of structure. It is generally useful when we need
multiple structure variables in our program.
Need for Array of Structures
Suppose we have 50 employees and we need to store the data of 50 employees. So for that, we need to define 50
variables of struct Employee type and store the data within that. However, declaring and handling the 50 variables is
not an easy task. Let’s imagine a bigger scenario, like 1000 employees.
So, if we declare the variable this way, it’s not possible to handle this.
struct Employee emp1, emp2, emp3, .. . ... . .. ... emp1000;
Declaration of Array of Structures
struct structure_name array_name [number_of_elements];
Initialization of Array of Structures
struct structure_name array_name [number_of_elements] = {
{element1_value1, element1_value2, ....},
{element2_value1, element2_value2, ....},
......
......
};
Structure Pointer in C
We can define a pointer that points to the structure like any other variable. Such pointers are generally
called Structure Pointers. We can access the members of the structure pointed by the structure pointer using the
( ->) arrow operator.
FILE MANAGEMENT
File handling in C is the process in which we create, open, read, write, and close operations
on a file. C language provides different functions such as fopen(), fwrite(), fread(), fseek(),
fprintf(), etc. to perform input, output, and many different C file operations in our program.
Types of Files in C
A file can be classified into two types based on the way the file stores the data. They are as
follows:
Text Files
A text file contains data in the form of ASCII characters and is generally used to store a
stream of characters.
Each line in a text file ends with a new line character (‘\n’).
It can be read or written by any text editor.
They are generally stored with .txt file extension.
Text files can also be used to store the source code.
Binary Files
A binary file contains data in binary form (i.e. 0’s and 1’s) instead of ASCII characters. They
contain data that is stored in a similar manner to how it is stored in the main memory.
The binary files can be created only from within a program and their contents can
only be read by a program.
More secure as they are not easily readable.
They are generally stored with .bin file extension.
C File Operations
C file operations refer to the different possible operations that we can perform on a file in C
such as:
1. Creating a new file – fopen() with attributes as “a” or “a+” or “w” or “w+”
2. Opening an existing file – fopen()
3. Reading from file – fscanf() or fgets()
4. Writing to a file – fprintf() or fputs()
5. Moving to a specific location in a file – fseek(), rewind()
6. Closing a file – fclose()
File Pointer in C
A file pointer is a reference to a particular position in the opened file. It is used in file
handling to perform all file operations such as read, write, close, etc. We use the FILE macro
to declare the file pointer variable. The FILE macro is defined inside <stdio.h> header file.
Syntax of File Pointer
FILE* pointer_name;
Open a File in C
For opening a file in C, the fopen() function is used with the filename or file path along with
the required access modes.
Syntax of fopen()
FILE* fopen(const char *file_name, const char *access_mode);
Parameters
file_name: name of the file when present in the same directory as the source file.
Otherwise, full path.
access_mode: Specifies for what operation the file is being opened.
Return Value
If the file is opened successfully, returns a file pointer to it.
If the file is not opened, then returns NULL.
File opening modes in C
Create a File in C
The fopen() function can not only open a file but also can create a file if it does not exist
already. For that, we have to use the modes that allow the creation of a file if not found
such as w, w+, wb, wb+, a, a+, ab, and ab+.
FILE *fptr;
fptr = fopen("filename.txt", "w");
Reading From a File
The file read operation in C can be performed using functions fscanf() or fgets(). Both the
functions performed the same operations as that of scanf and gets but with an additional
parameter, the file pointer. There are also other functions we can use to read from a file.
Such functions are listed below:
Write to a File
The file write operations can be performed by the functions fprintf() and fputs() with
similarities to read operations. C programming also provides some other functions that can
be used to write data to a file such as:
Closing a File
The fclose() function is used to close the file. After successful file operations, you must
always close a file to remove it from the memory.
Syntax of fclose()
fclose(file_pointer);
Read and Write in a Binary File
Till now, we have only discussed text file operations. The operations on a binary file are
similar to text file operations with little difference.
Opening a Binary File
To open a file in binary mode, we use the rb, rb+, ab, ab+, wb, and wb+ access mode in the
fopen() function. We also use the .bin file extension in the binary filename.
Example
fptr = fopen("filename.bin", "rb");
Write to a Binary File
We use fwrite() function to write data to a binary file. The data is written to the binary file
in the from of bits (0’s and 1’s).
Syntax of fwrite()
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE
*file_pointer);
Parameters:
ptr: pointer to the block of memory to be written.
size: size of each element to be written (in bytes).
nmemb: number of elements.
file_pointer: FILE pointer to the output file stream.
Reading from Binary File
The fread() function can be used to read data from a binary file in C. The data is read from
the file in the same form as it is stored i.e. binary form.
Syntax of fread()
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *file_pointer);
fseek() in C
If we have multiple records inside a file and need to access a particular record that is at a
specific position, so we need to loop through all the records before it to get the record.
Doing this will waste a lot of memory and operational time. To reduce memory
consumption and operational time we can use fseek() which provides an easier way to get
to the required data. fseek() function in C seeks the cursor to the given record in the file.
Syntax for fseek()
int fseek(FILE *ptr, long int offset, int pos);