0% found this document useful (0 votes)
8 views40 pages

Module 6&7

The document covers structures and file handling in C, explaining how to define and use structures, including nested structures and unions. It also details file operations such as creation, reading, writing, and types of files (text and binary), along with essential functions like fopen(), fclose(), fprintf(), and fscanf(). Additionally, it introduces preprocessor directives and their types, including macros and file inclusion.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views40 pages

Module 6&7

The document covers structures and file handling in C, explaining how to define and use structures, including nested structures and unions. It also details file operations such as creation, reading, writing, and types of files (text and binary), along with essential functions like fopen(), fclose(), fprintf(), and fscanf(). Additionally, it introduces preprocessor directives and their types, including macros and file inclusion.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

Module-6 & 7

Structure and File handling


Structure :
Structure in c is a user-defined data type that enables us to store
the collection of different data types. Each element of a structure is
called a member.
The ,struct keyword is used to define the structure.
Syntax: struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
Example:
struct Employee
{ int Eid;
char Ename[20];
float Esalary;
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:
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.

2. By declaring a 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)
Example:
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.
Nested Structure in C :
C provides us the feature of nesting one structure within another
structure by using which, complex data types are created

For example, we may need to store the address of an entity


employee in a structure. The attribute address may also have the
subparts as street number, city, state, and pin code. Hence, to
store the address of the employee, we need to store the address of
the employee into a separate structure and nest the structure
address into the structure employee. Consider the following
program.
Array of structures :
An array of structres in C can be defined as the collection of
multiple structures variables where each variable contains
information about different entities.
The array of structures in C are used to store information about
multiple entities of different data types. The array of structures is
also known as the collection of structures.
Passing structure to function :
We may pass the structure members into the function or pass the structure
variable at once
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.
The size of the union is based on the size of the largest member of the
union.

In the above code, union has two members, i.e., 'a'


and 'b'. The 'var' is a variable of union abc type. In
the main() method, we assign the 66 to 'a'
variable, so var.a will print 66 on the screen. Since
both 'a' and 'b' share the memory
location, var.b will print 'B' (ascii code of 66).
Difference between Structure and Union :
N.B :Advantage of union on structure is that, Union takes less memory space as
compared to the structure.
File handling :
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.
• Creation of the new file
• Opening an existing file
• Reading from the file
• Writing to the file
• Deleting the file

A list of file functions are given below:


Why do we need File Handling in C?

The use of file handling is exactly what the situation calls for.
In order to understand why file handling is important, let us look at a
few features of using files:
•Reusability: The data stored in the file can be accessed, updated,
and deleted anywhere and anytime providing high reusability.
•Portability: Without losing any data, files can be transferred to
another in the computer system. The risk of flawed coding is minimized
with this feature.
•Efficient: A large amount of input may be required for some
programs. File handling allows you to easily access a part of a file using
few instructions which saves a lot of time and reduces the chance of
errors.
•Storage Capacity: Files allow you to store a large amount of data
without having to worry about storing everything simultaneously in a
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
•Binary Files
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.
2. 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.
Note: Only fopen(), fclose(), fprintf(), fscanf(), fread() and fwrite() are in your syllabus
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.txt".
•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.
The fopen function works in the following way.
•Firstly, It searches the file to be opened.
•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.
•It sets up a character pointer which points to the first character of the file.
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()


The fprintf() function is used to write set of characters into file. It sends
formatted output to a stream.
int fprintf(FILE *stream, const char *format [, argument, ...])
Reading File : fscanf() :
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.

int fscanf(FILE *stream, const char *format [, argument, ...])


C File Example: Storing employee information :
Let's see a file handling example to store employee information as entered by user from console.
We are going to store id, name and salary of the employee.
Now open file from current directory. For windows operating system, go to TC\bin
directory, you will see emp.txt file. It will have following information.
fputc() function :
The fputc() function is used to write a single character into file. It outputs a
character to a stream.

int fputc(int c, FILE *stream)


Reading File : fgetc() function :
The fgetc() function returns a single character from the file. It gets a character
from the stream. It returns EOF at the end of file.
Syntax:
int fgetc(FILE *stream)
Writing File : fputs() function:
The fputs() function writes a line of characters into file. It outputs string to a stream.
Syntax:
int fputs(const char *s, FILE *stream)
Reading File : fgets() function
The fgets() function reads a line of characters from file. It gets string
from a stream.
Syntax:
char* fgets(char *s, int n, FILE *stream)
C fseek() function:
The fseek() function is used to set the file pointer to the specified
offset. It is used to write data into file at desired location.
int fseek(FILE *stream, long int offset, int origin)

here are 3 constants used in the


fseek() function for whence:
SEEK_SET, SEEK_CUR and SEEK_END.
•stream: It is a pointer to the FILE stream.
•offset: It specifies the number of bytes to
offset from the origin.
•origin: It indicates the position from where
the offset is calculated. It can be one of the
following:
• SEEK_SET: Beginning of the file.
• SEEK_CUR: Current position of the file
pointer.
• SEEK_END: End of the file.
C rewind() function :
The rewind() function sets the file pointer at the beginning of the stream. It is useful if
you have to use stream many times.
Syntax:
void rewind(FILE *stream)

C ftell() function :
The ftell() function returns the current file position of the specified stream.
Syntax:
long int ftell(FILE *stream)
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.
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 :
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:

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *file_pointer);


Parameters:
•ptr: pointer to the block of memory to read.

•size: the size of each element to read(in bytes).

•nmemb: number of elements.

•file_pointer: FILE pointer to the input file stream.


Preprocessor Directives :
The preprocessor directives are the instructions to the preprocessor for doing some tasks
such as text substitutions, macro expansions, including header files, and many more before
compiling the code.
All of these preprocessor directives begin with a ‘#’ hash symbol.
List of Preprocessor Directives :
Preprocessor Directives Description

#define Used to define a macro

#undef Used to undefine a macro

#include Used to include a file in the source code program

#ifdef Used to include a section of code if a certain macro is defined


by #define

#ifndef Used to include a section of code if a certain macro is not


defined by #define

#if Check for the specified condition

#else Alternate code that executes when #if fails

#elif Combines else and if for another condition check

#endif Used to mark the end of #if, #ifdef, and #ifndef


Types of C Preprocessors :
All the above preprocessors can be classified into 4 types, those are explained one by
one:
Macros :
Macros are used to define constants or create functions that are substituted by the
preprocessor before the code is compiled. The two
preprocessors #define and #undef are used to create and remove macros in C.
Example::
#include <stdio.h>

// Macro Definition
#define LIMIT 5

int main(){
for (int i = 0; i < LIMIT; i++) {
printf("%d \n", i);
}
return 0;
}
File Inclusion :
File inclusion allows you to include external files (header files, libraries, etc.) into the
current program. This is typically done using the #include directive.
There are two ways to include header files,
#include<filename>
#include”filename”
The ‘<‘ and ‘>’ brackets tell the compiler to look for the file in the standard
directory while double quotes ( ” ” ) tell the compiler to search for the header file in
the source file’s directory.
Example:
// Includes the standard I/O library
#include <stdio.h>

int main() {
printf("Hello World");

return 0;
}
Conditional Compilation :
allows you to include or exclude parts of the code depending on certain conditions.
There are the following conditional preprocessor directives: #if, #ifdef, #ifndef,
else, #elif and #endif.
#endif directive is used to close off the #if, #ifdef, and #ifndef opening directives.
Example:
#include <stdio.h>
// Defining a macro for PI
#define PI 3.14159
int main(){
// Check if PI is defined using #ifdef
#ifdef PI
printf("PI is defined\n");
// If PI is not defined, check if SQUARE is defined
#elif defined(SQUARE)
printf("Square is defined\n");
// If neither PI nor SQUARE is defined, trigger an error
#else
#error "Neither PI nor SQUARE is defined"
#endif
// Check if SQUARE is not defined using #ifndef
#ifndef SQUARE
printf("Square is not defined");
// If SQUARE is defined, print that it is defined
#else
printf("Square is defined");
#endif

return 0;
}

You might also like