SlideShare una empresa de Scribd logo
1 de 81
Descargar para leer sin conexión
Structures, Unions and File handling
by
Dr.T.P.Latchoumi
Structures
Structure is a user-defined datatype in C language which allows us to combine
data of different types together.
Structure helps to construct a complex data type which is more meaningful. It is
somewhat like an Array, but an array holds data of similar type only. But
structure on the other hand, can store data of any type, which is practical more
useful.
Structure is a group of variables of different data types represented by a single
name.
Defining a
structure
Syntax:
struct [structure_tag]
{
//member variable 1
//member variable 2
//member variable 3
...
}[structure_variables];
struct keyword is used to define a
structure. struct defines a new data
type which is a collection of
primary and derived datatypes.
Example
struct Student
{
char name[25];
int age;
char branch[10];
// F for female and M for male
char gender;
};
Here struct Student declares a structure to
hold the details of a student which consists
of 4 data fields, namely name, age, branch,
and gender.
These fields are called structure elements
or members.
Each member can have different datatype,
like in this case, name is an array of char
type and age is of int type etc.
Student is the name of the structure and is
called as the structure tag.
Declaring Structure Variables
It is possible to declare variables of a structure, either along with structure
definition or after the structure is defined.
Structure variable declaration is similar to the declaration of any normal variable
of any other datatype.
Structure variables can be declared in following two ways:
1. Declaring Structure variables separately
2. Declaring Structure variables with structure definition
Declaring
Structure
variables
separately
struct Student
{
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
};
struct Student S1, S2; //declaring variables of struct
Student
Declaring
Structure
variables with
structure
definition
struct Student
{
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
}S1, S2;
Here S1 and S2 are variables of structure Student. However
this approach is not much recommended.
Structure
Initialization
struct Patient
{
float height;
int weight;
int age;
};
struct Patient p1 = { 180.75 , 73, 23 }; //initialization
or,
struct Patient p1;
p1.height = 180.75; //initialization of each member separately
p1.weight = 73;
p1.age = 23;
Like a variable of any other
datatype, structure variable can also
be initialized at compile time.
Accessing Structure Members
Structure members can be accessed and assigned values in a number of ways.
Structure members have no meaning individually without the structure.
In order to assign a value to any structure member, the member name must be linked with the structure
variable using a dot . operator also called period or member access operator.
Access members of a structure. There are two types of operators used for accessing members of a
structure.
. - Member operator
-> - Structure pointer operator
Example 1
Example 2
Array of
Structures
We can also declare an array of
structure variables. in which each
element of the array will represent a
structure variable.
Example : struct employee emp[5];
The below program defines an array
emp of size 5.
Each element of the array emp is of
type Employee.
Example 2
Output:
10 20
Nested
Structures
Example
struct Student
{
char[30] name;
int age;
/* here Address is a structure */
struct Address
{
char[50] locality;
char[50] city;
int pincode;
}addr; };
Nested structure in C is nothing but
structure within structure. One
structure can be declared inside
other structure as we declare
structure members inside a
structure.
Nesting of structures is also
permitted in C language. Nested
structures mean, that one structure
has another structure as member
variable.
Structure within
structure in C
using normal
variable
This program explains how to use
structure within structure in C using
normal variable. “student_college_detail‟
structure is declared inside
“student_detail” structure in this
program. Both structure variables are
normal structure variables.
Please note that members of
“student_college_detail” structure are
accessed by 2 dot(.) operator and
members of “student_detail” structure
are accessed by single dot(.) operator.
STRUCTURE WITHIN
STRUCTURE
(NESTED
STRUCTURE IN C )
USING POINTER
VARIABLE
This program explains how to use
structure within structure in C using
pointer variable. “student_college_detail‟
structure is declared inside
“student_detail” structure in this
program. one normal structure variable
and one pointer structure variable is
used in this program.
Please note that combination of .(dot)
and ->(arrow) operators are used to
access the structure member which is
declared inside the structure.
Structure as
Function
Arguments
We can pass a structure as a
function argument just like we pass
any other variable or an array as a
function argument.
Structure
pointers
Like primitive types, we can have
pointer to a structure. If we have a
pointer to structure, members are
accessed using arrow ( -> )
operator.
Pointers to Structures
Define pointers to structures in the same way as you define pointer to any other variable −
struct Books *struct_pointer;
Now, you can store the address of a structure variable in the above defined pointer variable. To find the address of a
structure variable, place the '&'; operator before the structure's name as follows −
truct_pointer = &Book1;
To access the members of a structure using a pointer to that structure, you must use the → operator as follows −
struct_pointer->title;
Let us re-write the above example using structure pointer.
Example 1
Union
A union is a user-defined type
similar to structs in C except for one
key difference.
Structs allocate enough space to
store all its members wheres unions
allocate the space to store only the
largest member.
Cont…
Union and structure in C are same in concepts, except allocating memory for their members.
Structure allocates storage space for all its members separately.
Whereas, Union allocates one common storage space for all its members
We can access only one member of union at a time. We can‟t access all member values at the same time in union. But,
structure can access all member values at the same time. This is because, Union allocates one common storage space for
all its members. Where as Structure allocates storage space for all its members separately.
Many union variables can be created in a program and memory will be allocated for each union variable separately.
Below table will help you how to form a C union, declare a union, initializing and accessing the members of the union.
Difference
between Normal
and pointer
variable
Define unions
union car
{
char name[50];
int price;
};
The above code defines a derived type union car.
Create union
variables
When a union is defined, it
creates a user-defined type.
However, no memory is allocated.
To allocate memory for a given
union type and work with it, we
need to create variables.
Here's how we create union
variables.
Example
Access
members of a
union
We use the . operator to access
members of a union. To access
pointer variables, we use also use
the -> operator.
Difference between union and
structure
Example
Pointers to
union
Like structures, we can have
pointers to unions and can access
members using the arrow operator
(->).
The following example
demonstrates the same.
File Management 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. Also, we can extract/fetch data from a file to work with it in
the program. The operations that you can perform on a File in C are −
Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”)
Opening an existing file (fopen)
Reading from file (fscanf or fgets)
Writing to a file (fprintf or fputs)
Moving to a specific location in a file (fseek, rewind)
Closing a file (fclose)
Creating or
opening file
using fopen()
“r” – Searches file. If the file is opened successfully fopen( ) loads it into
memory and sets up a pointer which points to the first character in it. If the
file cannot be opened fopen( ) returns NULL.
“w” – Searches file. If the file exists, its contents are overwritten. If the file
doesn‟t exist, a new file is created. Returns NULL, if unable to open file.
“a” – Searches file. If the file is opened successfully fopen( ) loads it into
memory and sets up a pointer that points to the last character in it. If the file
doesn‟t exist, a new file is created. Returns NULL, if unable to open file.
“r+” – Searches file. If is opened successfully fopen( ) loads it into memory
and sets up a pointer which points to the first character in it. Returns NULL,
if unable to open the file.
“w+” – Searches file. If the file exists, its contents are overwritten. If the file
doesn‟t exist a new file is created. Returns NULL, if unable to open file.
“a+” – Searches file. If the file is opened successfully fopen( ) loads it into
memory and sets up a pointer which points to the last character in it. If the
file doesn‟t exist, a new file is created. Returns NULL, if unable to open
file.
The fopen() function is used to
create a new file or open an existing
file in C. The fopen function is
defined in the stdio.h header file.
Now, lets see the syntax for creation
of a new file or opening a file
file = fopen(“file_name”, “mode”)
This is a common syntax for both
opening and creating a file in C.
Mode = “r”
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "r")){
printf("File opened successfully in read mode");
}
else
printf("The file is not present! cannot create a new file using r mode");
fclose(file);
return 0;
}
Output: File opened successfully in read mode
open for reading, this mode will
open the file for reading purpose
only, i.e. the contents can only be
viewed, nothing else like edits can
be done to it.
This mode cannot create a new
file and open () returns NULL, if
we try to create a new file using
this mode.
Mode = “rb”
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("program.txt", "rb")){
printf("File opened successfully in read mode");
}
else
printf("The file is not present! cannot create a new file using rb mode");
fclose(file);
return 0;
}
Output
The file is not present! cannot create a new file using rb mode
open for reading in binary mode,
this mode will open the file for
reading in binary mode only, i.e.,
the contents can only be viewed
and nothing else like edits can be
done to it.
This mode cannot create a new
file and open () returns NULL, if
we try to create a new file using
this mode.
Mode = “w”
open for writing only, this mode will
open the file if present in the
current directory for writing only i.e.
reading operation cannot be
performed. If the file is not present
in the current directory, the program
will create a new file and open it for
writing.
If we open a file that contains some
text in it, the contents will be
overwritten.
Mode = “wb”
open for writing in binary mode,
this mode will open the file if
present in the current directory for
writing in binary mode i.e. reading
operation cannot be performed.
If the file is not present in the
current directory, the program will
create a new file and open it for
writing in binary mode.
Mode = “a”
open for append only, this mode will
open the file if present in the current
directory for writing only i.e. reading
operation cannot be performed.
If the file is not present in the current
directory, the program will create a new
file and open it for writing.
If we open a file that contains some text
in it, the contents will not be overwritten;
instead the new text will be added after
the existing text in the file.
Mode = “ab”
open for append in binary, this mode will
open the file if present in the current
directory for writing in binary only i.e.
reading operation cannot be performed.
If the file is not present in the current
directory, the program will create a new file
and open it for writing in binary.
If we open a file that contains some text in
it, the contents will not be overwritten;
instead the new text will be added after the
existing text in the file.
Mode = “r+”
open for reading and writing both,
this mode will open the file for both
reading and writing purposes i.e.
both read and write operations can
be performed to the file.
This mode cannot create a new file
and open() returns NULL, if we try to
create a new file using this mode.
If we open a file that contains some
text in it and write something, the
contents will be overwritten.
Mode = “rb+”
open for reading in binary mode, this
mode will open the file for reading in
binary mode only, i.e. the contents can
only be viewed and nothing else like edits
can be done to it.
This mode cannot create a new file and
open() returns NULL, if we try to create a
new file using this mode.
If we open a file that contains some text
in it and write something, the contents
will be overwritten.
Mode = “w+”
open for writing and reading, this
mode will open the file if present in
the current directory for writing and
reading operation both.
If the file is not present in the current
directory, the program will create a
new file and open it for reading and
writing.
If we open a file that contains some
text in it, the contents will be
overwritten.
Mode = “wb+”
open for writing and reading in binary
mode, this mode will open the file if
present in the current directory for
writing and reading in binary mode.
If the file is not present in the current
directory, the program will create a
new file and open it for reading and
writing in binary mode.
If we open a file that contains some
text in it, the contents will be
overwritten.
Mode = “a+”
open for read and append, this mode
will open the file if present in the
current directory for both reading and
writing.
If the file is not present in the current
directory, the program will create a
new file and open it for reading and
writing.
If we open a file that contains some
text in it, the contents will not be
overwritten; instead the new text will
be added after the existing text in the
file.
Mode = “ab+”
open for read and append in binary, this
mode will open the file if present in the
current directory for both reading and
writing in binary.
If the file is not present in the current
directory, the program will create a new file
and open it for reading and writing in
binary.
If we open a file that contains some text in
it, the contents will not be overwritten;
instead the new text will be added after the
existing text in the file.
Reading Data for from an
existing file
We can read content of a file in c using the
fscanf() and fgets() and fgetc() functions. All are
used to read contents of a file. Let‟s see the
working of each of the function −
fscanf()
The fscanf() function is used to read character
set i.e strings from the file. It returns the EOF,
when all the content of the file are read by it.
Syntax
int fscanf(FILE *stream, const char
*charPointer[])
Parameters
FILE *stream: the pointer to the opened file.
const char *charPointer[]: string of character.
fgets()
The fget() function in C is used to
read string from the stream.
Syntax
char* fgets(char *string, int length,
FILE *stream)
Parameter
char *string: It is a string which will
store the data from the string.
int length: It is an int which gives the
length of string to be considered.
FILE *stream: It is the pointer to the
opened file.
fgetc()
The fgetc() function in C is used to
return a single character from the
file. It gets a character from the file
and returns EOF at the end of file.
Syntax
char* fgetc(FILE *stream)
Parameter
FILE *stream: It is the pointer to the
opened file.
Writing Data to
a file in C
We can write data to a file in C using the
fprintf(), fputs(), fputc() functions. All are used
to write contents to a file.
Let‟s see the working of each of the function −
fprintf()
The fprintf() function is used to write data to a
file. It writes a set of characters in a file.
Syntax
int fprintf(FILE *stream, char *string[])
Parameters
FILE for *stream: It is the pointer to the opened
file.
char *string[]: It is the character array that we
want to write in the file.
fputf()
The fputf() function in C can be used to write
to a file. It is used to write a line (character
line) to the file.
Syntax
int fputs(const char *string, FILE *stream)
Parameters
Constant char *string[]: It is the character
array that we want to write in the file.
FILE for *stream: It is the pointer to the
opened file.
fputc()
The fputc() function is used to write a
single character to the file.
Syntax
int fputc(char character , FILE *stream)
Parameters
char character : It is the character that
we want to write in the file.
FILE for *stream: It is the pointer to the
opened file.
Closing of
files
fclose()
The fclose() function is used to close the
open file. We should close the file after
performing operations on it to save the
operations that we have applied to it.
Syntax
fclose(FILE *stream)
Parameters
FILE for *stream: It is the pointer to the
opened file
FILES access
It is necessary to keep data in the permanent storage because it is difficult to handle the large volume of data by programs
and after execution of program is over all the entered data will be lost because, the data stored in the variables are
temporary. C supports the concept of file through which the data can be stored in the disk or secondary storage device. So
the data can be read when required. A file is a collection of data or text, placed on the disk.
There are two types of files- sequential file and random access file. In sequential file, data are kept sequential. As
example if we want to access the forty fourth record, then first forty three records should be read sequentially to reach the
forty fourth record. In the record access file, the data can be accessed and processed randomly i.e in this case the forty
fourth record can be accessed directly. It takes less time than the sequential file.
Hence depending up on the method of accessing the data stored ,there are two types of files.
1. Sequential file
2. Random access file
Cont…
1.Sequential File: In this type of files data is kept in sequential order if we want to read the last record
of the file,we need to read all records before that record, so it takes more time.
2.Random access Files: In this type of files data can be read and modified randomly. If we want to
read the last record we can read it directly.
It takes less time when compared to sequential file.
Sequential
file access in
C
C Program to do the operations of
Sequential file with records.
Sequential file, A file which consists of the
same record types that is stored on a
secondary storage device.
The physical sequence of records may be
based upon sorting values of one or more
data items or fields.
Here we are creating, Reading, searching
the sequential file, using c file i/o
operations.
Cont…
cont…
Random access file
There is no need to read each record sequentially, if we want to access a particular record.C
supports these functions for random access file processing.
fseek()
ftell()
rewind()
fseek()
This function is used for seeking the pointer position in the file at the specified byte.
Syntax:fseek( file pointer, displacement, pointer position);
Where , file pointer ---- It is the pointer which points to the file.
displacement ---- It is positive or negative.This is the number of bytes which are skipped backward (if negative) or forward( if positive)
from the current position.This is attached with L because this is a long integer.
Pointer position:This sets the pointer position in the file.
Value pointer position
0 Beginning of file.
1 Current position
2 End of file
fseek() operations
Example
OUTPUT: It depends on the content
in the file.
ftell()
This function returns the current
position of the file position pointer.
The value is counted from the
beginning of the file.
Syntax
long ftell(FILE *fp);
rewind()
This function is used to move the
file pointer to the beginning of the
file. This function is useful when
we open file for update.
Syntax:
rewind(FILE *fp);
Here, fp is file pointer of type FILE
C Pre-processor Directives
The C Preprocessor is not a part of the compiler but is a separate step in the compilation process.
In simple terms, a C Preprocessor is just a text substitution tool and it instructs the compiler to do
required pre-processing before the actual compilation. We will refer to the C Preprocessor as CPP.
All preprocessor commands begin with a hash symbol (#). It must be the first nonblank character,
and for readability, a preprocessor directive should begin in the first column. The following section
lists down all the important preprocessor directives –
Directives and
description
Cont…
Predefined
Macros
ANSI C defines a number of
macros. Although each one is
available for use in programming,
the predefined macros should not
be directly modified
Example
Preprocessor Operators
The Macro Continuation () Operator
A macro is normally confined to a single line. The macro continuation operator () is used to
continue a macro that is too long for a single line. For example −
#define message_for(a, b) 
printf(#a " and " #b ": We love you!n")
The Stringize
(#) Operator
#include <stdio.h>
#define message_for(a, b) 
printf(#a " and " #b ": We love you!n")
int main(void) {
message_for(Carole, Debra);
return 0;
}
Output
Carole and Debra: We love you!
The stringize or number-sign
operator ( '#' ), when used within a
macro definition, converts a macro
parameter into a string constant.
This operator may be used only in a
macro having a specified argument
or parameter list. For example –
The Token
Pasting (##)
Operator
#include <stdio.h>
#define tokenpaster(n) printf ("token" #n " = %d",
token##n)
int main(void) {
int token34 = 40;
tokenpaster(34);
return 0;
}
Output
token34 = 40
The token-pasting operator (##)
within a macro definition
combines two arguments.
It permits two separate tokens in
the macro definition to be joined
into a single token. For example –
The Defined()
Operator
#include <stdio.h>
#if !defined (MESSAGE)
#define MESSAGE "You wish!"
#endif
int main(void) {
printf("Here is the message: %sn", MESSAGE);
return 0;
}
Output
Here is the message: You wish!
The preprocessor defined operator
is used in constant expressions to
determine if an identifier is defined
using #define.
If the specified identifier is defined,
the value is true (non-zero). If the
symbol is not defined, the value is
false (zero).
The defined operator is specified as
follows –
Parameterized
Macros
One of the powerful functions of the CPP
is the ability to simulate functions using
parameterized macros.
For example, we might have some code
to square a number as follows −
int square(int x) {
return x * x;
}
We can rewrite above the code using a
macro as follows −
#define square(x) ((x) * (x))
Types
There are 4 main types of preprocessor directives:
Macros
File Inclusion
Conditional Compilation
Other directives
Macros
Macros are a piece of code in a
program which is given some
name. Whenever this name is
encountered by the compiler the
compiler replaces the name with
the actual piece of code.
The „#define‟ directive is used to
define a macro. Let us now
understand the macro definition
with the help of a program:
Macros with
arguments
We can also pass arguments to
macros.
Macros defined with arguments
works similarly as functions.
Let us understand this with a
program:
File Inclusion
Header File or Standard files: These files contains definition of pre-
defined functions like printf(), scanf() etc. These files must be included
for working with these functions. Different function are declared in
different header files. For example standard I/O functions are in
„iostream‟ file whereas functions which perform string operations are
in „string‟ file.
Syntax:
#include<file_name>
where file_name is the name of file to be included. The „<„ and „>‟
brackets tells the compiler to look for the file in standard directory.
user defined files: When a program becomes very large, it is good
practice to divide it into smaller files and include whenever needed.
These types of files are user defined files. These files can be included
as:
#include"filename"
This type of preprocessor directive
tells the compiler to include a file
in the source code program.
There are two types of files which
can be included by the user in the
program:
Conditional
Compilation
Syntax:
#ifdef macro_name
statement1;
statement2;
statement3;
.
.
.
statementN;
#endif
If the macro with name as „macroname„ is defined then the block of
statements will execute normally but if it is not defined, the compiler will
simply skip this block of statements.
Conditional Compilation directives
are type of directives which helps
to compile a specific portion of the
program or to skip compilation of
some specific part of the program
based on some conditions.
This can be done with the help of
two preprocessing commands
„ifdef„ and „endif„.
Other
directives
#undef Directive: The #undef directive is used to undefine an
existing macro. This directive works as:
#undef LIMIT
Using this statement will undefine the existing macro LIMIT.
After this statement every “#ifdef LIMIT” statement will
evaluate to false.
#pragma Directive: This directive is a special purpose
directive and is used to turn on or off some features. This type
of directives are compiler-specific, i.e., they vary from
compiler to compiler. Some of the #pragma directives are
discussed below:
#pragma startup and #pragma exit: These directives helps us to
specify the functions that are needed to run before program
startup( before the control passes to main()) and just before
program exit (just before the control returns from main()).
Apart from the above directives
there are two more directives
which are not commonly used.
These are:
Example
Cont…
#pragma warn Directive: This directive is used to hide the
warning message which are displayed during compilation.
We can hide the warnings as shown below:
#pragma warn -rvl: This directive hides those warning
which are raised when a function which is supposed to
return a value does not returns a value.
#pragma warn -par: This directive hides those warning
which are raised when a function does not uses the
parameters passed to it.
#pragma warn -rch: This directive hides those warning
which are raised when a code is unreachable. For example:
any code written after the return statement in a function is
unreachable.
Unit 3

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Unit 9. Structure and Unions
Unit 9. Structure and UnionsUnit 9. Structure and Unions
Unit 9. Structure and Unions
 
Presentation on c programing satcture
Presentation on c programing satcture Presentation on c programing satcture
Presentation on c programing satcture
 
Class objects oopm
Class objects oopmClass objects oopm
Class objects oopm
 
DATA BASE MANAGEMENT SYSTEM - SHORT NOTES
DATA BASE MANAGEMENT SYSTEM - SHORT NOTESDATA BASE MANAGEMENT SYSTEM - SHORT NOTES
DATA BASE MANAGEMENT SYSTEM - SHORT NOTES
 
C programming structures &amp; union
C programming structures &amp; unionC programming structures &amp; union
C programming structures &amp; union
 
Structure in C language
Structure in C languageStructure in C language
Structure in C language
 
Database Systems - Normalization of Relations(Chapter 4/3)
Database Systems - Normalization of Relations(Chapter 4/3)Database Systems - Normalization of Relations(Chapter 4/3)
Database Systems - Normalization of Relations(Chapter 4/3)
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 
12 SQL
12 SQL12 SQL
12 SQL
 
Lecture 3.mte 407
Lecture 3.mte 407Lecture 3.mte 407
Lecture 3.mte 407
 
The Fuzzy Logical Databases
The Fuzzy Logical DatabasesThe Fuzzy Logical Databases
The Fuzzy Logical Databases
 
Islamic University Previous Year Question Solution 2018 (ADBMS)
Islamic University Previous Year Question Solution 2018 (ADBMS)Islamic University Previous Year Question Solution 2018 (ADBMS)
Islamic University Previous Year Question Solution 2018 (ADBMS)
 
When to use a structure vs classes in c++
When to use a structure vs classes in c++When to use a structure vs classes in c++
When to use a structure vs classes in c++
 
Overview of Object-Oriented Concepts Characteristics by vikas jagtap
Overview of Object-Oriented Concepts Characteristics by vikas jagtapOverview of Object-Oriented Concepts Characteristics by vikas jagtap
Overview of Object-Oriented Concepts Characteristics by vikas jagtap
 
C# program structure
C# program structureC# program structure
C# program structure
 
Structure in c
Structure in cStructure in c
Structure in c
 
Databases: Normalisation
Databases: NormalisationDatabases: Normalisation
Databases: Normalisation
 
Oodbms ch 20
Oodbms ch 20Oodbms ch 20
Oodbms ch 20
 
Chapt 1 odbms
Chapt 1 odbmsChapt 1 odbms
Chapt 1 odbms
 
Unit 4 qba
Unit 4 qbaUnit 4 qba
Unit 4 qba
 

Similar a Unit 3

Chapter 13.1.9
Chapter 13.1.9Chapter 13.1.9
Chapter 13.1.9
patcha535
 

Similar a Unit 3 (20)

Structures in c++
Structures in c++Structures in c++
Structures in c++
 
Presentation on c structures
Presentation on c   structures Presentation on c   structures
Presentation on c structures
 
Structure & union
Structure & unionStructure & union
Structure & union
 
My c++
My c++My c++
My c++
 
5 Structure & File.pptx
5 Structure & File.pptx5 Structure & File.pptx
5 Structure & File.pptx
 
Introduction to Data Structure : Pointer
Introduction to Data Structure : PointerIntroduction to Data Structure : Pointer
Introduction to Data Structure : Pointer
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Structure in c language
Structure in c languageStructure in c language
Structure in c language
 
UNIONS.pptx
UNIONS.pptxUNIONS.pptx
UNIONS.pptx
 
struct and class deferences
 struct and class deferences struct and class deferences
struct and class deferences
 
Structures
StructuresStructures
Structures
 
Chapter 8 Structure Part 2 (1).pptx
Chapter 8 Structure Part 2 (1).pptxChapter 8 Structure Part 2 (1).pptx
Chapter 8 Structure Part 2 (1).pptx
 
Technical Interview
Technical InterviewTechnical Interview
Technical Interview
 
Structures and Pointers
Structures and PointersStructures and Pointers
Structures and Pointers
 
C structure and union
C structure and unionC structure and union
C structure and union
 
Easy Understanding of Structure Union Typedef Enum in C Language.pdf
Easy Understanding of Structure Union Typedef Enum in C Language.pdfEasy Understanding of Structure Union Typedef Enum in C Language.pdf
Easy Understanding of Structure Union Typedef Enum in C Language.pdf
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Programming in C
Programming in CProgramming in C
Programming in C
 
Pointers and Structures
Pointers and StructuresPointers and Structures
Pointers and Structures
 
Chapter 13.1.9
Chapter 13.1.9Chapter 13.1.9
Chapter 13.1.9
 

Más de TPLatchoumi (9)

Unit 2
Unit 2Unit 2
Unit 2
 
Unit iii
Unit iiiUnit iii
Unit iii
 
Unit i
Unit iUnit i
Unit i
 
Unit ii
Unit iiUnit ii
Unit ii
 
Unit 1
Unit 1Unit 1
Unit 1
 
Unit v
Unit vUnit v
Unit v
 
Unit iv
Unit ivUnit iv
Unit iv
 
Coa
Coa Coa
Coa
 
17 cs002
17 cs00217 cs002
17 cs002
 

Último

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 

Último (20)

Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 

Unit 3

  • 1. Structures, Unions and File handling by Dr.T.P.Latchoumi
  • 2. Structures Structure is a user-defined datatype in C language which allows us to combine data of different types together. Structure helps to construct a complex data type which is more meaningful. It is somewhat like an Array, but an array holds data of similar type only. But structure on the other hand, can store data of any type, which is practical more useful. Structure is a group of variables of different data types represented by a single name.
  • 3. Defining a structure Syntax: struct [structure_tag] { //member variable 1 //member variable 2 //member variable 3 ... }[structure_variables]; struct keyword is used to define a structure. struct defines a new data type which is a collection of primary and derived datatypes.
  • 4. Example struct Student { char name[25]; int age; char branch[10]; // F for female and M for male char gender; }; Here struct Student declares a structure to hold the details of a student which consists of 4 data fields, namely name, age, branch, and gender. These fields are called structure elements or members. Each member can have different datatype, like in this case, name is an array of char type and age is of int type etc. Student is the name of the structure and is called as the structure tag.
  • 5. Declaring Structure Variables It is possible to declare variables of a structure, either along with structure definition or after the structure is defined. Structure variable declaration is similar to the declaration of any normal variable of any other datatype. Structure variables can be declared in following two ways: 1. Declaring Structure variables separately 2. Declaring Structure variables with structure definition
  • 6. Declaring Structure variables separately struct Student { char name[25]; int age; char branch[10]; //F for female and M for male char gender; }; struct Student S1, S2; //declaring variables of struct Student
  • 7. Declaring Structure variables with structure definition struct Student { char name[25]; int age; char branch[10]; //F for female and M for male char gender; }S1, S2; Here S1 and S2 are variables of structure Student. However this approach is not much recommended.
  • 8. Structure Initialization struct Patient { float height; int weight; int age; }; struct Patient p1 = { 180.75 , 73, 23 }; //initialization or, struct Patient p1; p1.height = 180.75; //initialization of each member separately p1.weight = 73; p1.age = 23; Like a variable of any other datatype, structure variable can also be initialized at compile time.
  • 9. Accessing Structure Members Structure members can be accessed and assigned values in a number of ways. Structure members have no meaning individually without the structure. In order to assign a value to any structure member, the member name must be linked with the structure variable using a dot . operator also called period or member access operator. Access members of a structure. There are two types of operators used for accessing members of a structure. . - Member operator -> - Structure pointer operator
  • 12. Array of Structures We can also declare an array of structure variables. in which each element of the array will represent a structure variable. Example : struct employee emp[5]; The below program defines an array emp of size 5. Each element of the array emp is of type Employee.
  • 14. Nested Structures Example struct Student { char[30] name; int age; /* here Address is a structure */ struct Address { char[50] locality; char[50] city; int pincode; }addr; }; Nested structure in C is nothing but structure within structure. One structure can be declared inside other structure as we declare structure members inside a structure. Nesting of structures is also permitted in C language. Nested structures mean, that one structure has another structure as member variable.
  • 15. Structure within structure in C using normal variable This program explains how to use structure within structure in C using normal variable. “student_college_detail‟ structure is declared inside “student_detail” structure in this program. Both structure variables are normal structure variables. Please note that members of “student_college_detail” structure are accessed by 2 dot(.) operator and members of “student_detail” structure are accessed by single dot(.) operator.
  • 16. STRUCTURE WITHIN STRUCTURE (NESTED STRUCTURE IN C ) USING POINTER VARIABLE This program explains how to use structure within structure in C using pointer variable. “student_college_detail‟ structure is declared inside “student_detail” structure in this program. one normal structure variable and one pointer structure variable is used in this program. Please note that combination of .(dot) and ->(arrow) operators are used to access the structure member which is declared inside the structure.
  • 17. Structure as Function Arguments We can pass a structure as a function argument just like we pass any other variable or an array as a function argument.
  • 18. Structure pointers Like primitive types, we can have pointer to a structure. If we have a pointer to structure, members are accessed using arrow ( -> ) operator.
  • 19. Pointers to Structures Define pointers to structures in the same way as you define pointer to any other variable − struct Books *struct_pointer; Now, you can store the address of a structure variable in the above defined pointer variable. To find the address of a structure variable, place the '&'; operator before the structure's name as follows − truct_pointer = &Book1; To access the members of a structure using a pointer to that structure, you must use the → operator as follows − struct_pointer->title; Let us re-write the above example using structure pointer.
  • 21. Union A union is a user-defined type similar to structs in C except for one key difference. Structs allocate enough space to store all its members wheres unions allocate the space to store only the largest member.
  • 22. Cont… Union and structure in C are same in concepts, except allocating memory for their members. Structure allocates storage space for all its members separately. Whereas, Union allocates one common storage space for all its members We can access only one member of union at a time. We can‟t access all member values at the same time in union. But, structure can access all member values at the same time. This is because, Union allocates one common storage space for all its members. Where as Structure allocates storage space for all its members separately. Many union variables can be created in a program and memory will be allocated for each union variable separately. Below table will help you how to form a C union, declare a union, initializing and accessing the members of the union.
  • 24. Define unions union car { char name[50]; int price; }; The above code defines a derived type union car.
  • 25. Create union variables When a union is defined, it creates a user-defined type. However, no memory is allocated. To allocate memory for a given union type and work with it, we need to create variables. Here's how we create union variables.
  • 27. Access members of a union We use the . operator to access members of a union. To access pointer variables, we use also use the -> operator.
  • 28. Difference between union and structure
  • 30. Pointers to union Like structures, we can have pointers to unions and can access members using the arrow operator (->). The following example demonstrates the same.
  • 31. File Management 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. Also, we can extract/fetch data from a file to work with it in the program. The operations that you can perform on a File in C are − Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”) Opening an existing file (fopen) Reading from file (fscanf or fgets) Writing to a file (fprintf or fputs) Moving to a specific location in a file (fseek, rewind) Closing a file (fclose)
  • 32. Creating or opening file using fopen() “r” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the first character in it. If the file cannot be opened fopen( ) returns NULL. “w” – Searches file. If the file exists, its contents are overwritten. If the file doesn‟t exist, a new file is created. Returns NULL, if unable to open file. “a” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that points to the last character in it. If the file doesn‟t exist, a new file is created. Returns NULL, if unable to open file. “r+” – Searches file. If is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the first character in it. Returns NULL, if unable to open the file. “w+” – Searches file. If the file exists, its contents are overwritten. If the file doesn‟t exist a new file is created. Returns NULL, if unable to open file. “a+” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the last character in it. If the file doesn‟t exist, a new file is created. Returns NULL, if unable to open file. The fopen() function is used to create a new file or open an existing file in C. The fopen function is defined in the stdio.h header file. Now, lets see the syntax for creation of a new file or opening a file file = fopen(“file_name”, “mode”) This is a common syntax for both opening and creating a file in C.
  • 33. Mode = “r” #include <stdio.h> int main(){ FILE * file; if (file = fopen("hello.txt", "r")){ printf("File opened successfully in read mode"); } else printf("The file is not present! cannot create a new file using r mode"); fclose(file); return 0; } Output: File opened successfully in read mode open for reading, this mode will open the file for reading purpose only, i.e. the contents can only be viewed, nothing else like edits can be done to it. This mode cannot create a new file and open () returns NULL, if we try to create a new file using this mode.
  • 34. Mode = “rb” #include <stdio.h> int main(){ FILE * file; if (file = fopen("program.txt", "rb")){ printf("File opened successfully in read mode"); } else printf("The file is not present! cannot create a new file using rb mode"); fclose(file); return 0; } Output The file is not present! cannot create a new file using rb mode open for reading in binary mode, this mode will open the file for reading in binary mode only, i.e., the contents can only be viewed and nothing else like edits can be done to it. This mode cannot create a new file and open () returns NULL, if we try to create a new file using this mode.
  • 35. Mode = “w” open for writing only, this mode will open the file if present in the current directory for writing only i.e. reading operation cannot be performed. If the file is not present in the current directory, the program will create a new file and open it for writing. If we open a file that contains some text in it, the contents will be overwritten.
  • 36. Mode = “wb” open for writing in binary mode, this mode will open the file if present in the current directory for writing in binary mode i.e. reading operation cannot be performed. If the file is not present in the current directory, the program will create a new file and open it for writing in binary mode.
  • 37. Mode = “a” open for append only, this mode will open the file if present in the current directory for writing only i.e. reading operation cannot be performed. If the file is not present in the current directory, the program will create a new file and open it for writing. If we open a file that contains some text in it, the contents will not be overwritten; instead the new text will be added after the existing text in the file.
  • 38. Mode = “ab” open for append in binary, this mode will open the file if present in the current directory for writing in binary only i.e. reading operation cannot be performed. If the file is not present in the current directory, the program will create a new file and open it for writing in binary. If we open a file that contains some text in it, the contents will not be overwritten; instead the new text will be added after the existing text in the file.
  • 39. Mode = “r+” open for reading and writing both, this mode will open the file for both reading and writing purposes i.e. both read and write operations can be performed to the file. This mode cannot create a new file and open() returns NULL, if we try to create a new file using this mode. If we open a file that contains some text in it and write something, the contents will be overwritten.
  • 40. Mode = “rb+” open for reading in binary mode, this mode will open the file for reading in binary mode only, i.e. the contents can only be viewed and nothing else like edits can be done to it. This mode cannot create a new file and open() returns NULL, if we try to create a new file using this mode. If we open a file that contains some text in it and write something, the contents will be overwritten.
  • 41. Mode = “w+” open for writing and reading, this mode will open the file if present in the current directory for writing and reading operation both. If the file is not present in the current directory, the program will create a new file and open it for reading and writing. If we open a file that contains some text in it, the contents will be overwritten.
  • 42. Mode = “wb+” open for writing and reading in binary mode, this mode will open the file if present in the current directory for writing and reading in binary mode. If the file is not present in the current directory, the program will create a new file and open it for reading and writing in binary mode. If we open a file that contains some text in it, the contents will be overwritten.
  • 43. Mode = “a+” open for read and append, this mode will open the file if present in the current directory for both reading and writing. If the file is not present in the current directory, the program will create a new file and open it for reading and writing. If we open a file that contains some text in it, the contents will not be overwritten; instead the new text will be added after the existing text in the file.
  • 44. Mode = “ab+” open for read and append in binary, this mode will open the file if present in the current directory for both reading and writing in binary. If the file is not present in the current directory, the program will create a new file and open it for reading and writing in binary. If we open a file that contains some text in it, the contents will not be overwritten; instead the new text will be added after the existing text in the file.
  • 45. Reading Data for from an existing file We can read content of a file in c using the fscanf() and fgets() and fgetc() functions. All are used to read contents of a file. Let‟s see the working of each of the function − fscanf() The fscanf() function is used to read character set i.e strings from the file. It returns the EOF, when all the content of the file are read by it. Syntax int fscanf(FILE *stream, const char *charPointer[]) Parameters FILE *stream: the pointer to the opened file. const char *charPointer[]: string of character.
  • 46. fgets() The fget() function in C is used to read string from the stream. Syntax char* fgets(char *string, int length, FILE *stream) Parameter char *string: It is a string which will store the data from the string. int length: It is an int which gives the length of string to be considered. FILE *stream: It is the pointer to the opened file.
  • 47. fgetc() The fgetc() function in C is used to return a single character from the file. It gets a character from the file and returns EOF at the end of file. Syntax char* fgetc(FILE *stream) Parameter FILE *stream: It is the pointer to the opened file.
  • 48. Writing Data to a file in C We can write data to a file in C using the fprintf(), fputs(), fputc() functions. All are used to write contents to a file. Let‟s see the working of each of the function − fprintf() The fprintf() function is used to write data to a file. It writes a set of characters in a file. Syntax int fprintf(FILE *stream, char *string[]) Parameters FILE for *stream: It is the pointer to the opened file. char *string[]: It is the character array that we want to write in the file.
  • 49. fputf() The fputf() function in C can be used to write to a file. It is used to write a line (character line) to the file. Syntax int fputs(const char *string, FILE *stream) Parameters Constant char *string[]: It is the character array that we want to write in the file. FILE for *stream: It is the pointer to the opened file.
  • 50. fputc() The fputc() function is used to write a single character to the file. Syntax int fputc(char character , FILE *stream) Parameters char character : It is the character that we want to write in the file. FILE for *stream: It is the pointer to the opened file.
  • 51. Closing of files fclose() The fclose() function is used to close the open file. We should close the file after performing operations on it to save the operations that we have applied to it. Syntax fclose(FILE *stream) Parameters FILE for *stream: It is the pointer to the opened file
  • 52. FILES access It is necessary to keep data in the permanent storage because it is difficult to handle the large volume of data by programs and after execution of program is over all the entered data will be lost because, the data stored in the variables are temporary. C supports the concept of file through which the data can be stored in the disk or secondary storage device. So the data can be read when required. A file is a collection of data or text, placed on the disk. There are two types of files- sequential file and random access file. In sequential file, data are kept sequential. As example if we want to access the forty fourth record, then first forty three records should be read sequentially to reach the forty fourth record. In the record access file, the data can be accessed and processed randomly i.e in this case the forty fourth record can be accessed directly. It takes less time than the sequential file. Hence depending up on the method of accessing the data stored ,there are two types of files. 1. Sequential file 2. Random access file
  • 53. Cont… 1.Sequential File: In this type of files data is kept in sequential order if we want to read the last record of the file,we need to read all records before that record, so it takes more time. 2.Random access Files: In this type of files data can be read and modified randomly. If we want to read the last record we can read it directly. It takes less time when compared to sequential file.
  • 54. Sequential file access in C C Program to do the operations of Sequential file with records. Sequential file, A file which consists of the same record types that is stored on a secondary storage device. The physical sequence of records may be based upon sorting values of one or more data items or fields. Here we are creating, Reading, searching the sequential file, using c file i/o operations.
  • 57. Random access file There is no need to read each record sequentially, if we want to access a particular record.C supports these functions for random access file processing. fseek() ftell() rewind()
  • 58. fseek() This function is used for seeking the pointer position in the file at the specified byte. Syntax:fseek( file pointer, displacement, pointer position); Where , file pointer ---- It is the pointer which points to the file. displacement ---- It is positive or negative.This is the number of bytes which are skipped backward (if negative) or forward( if positive) from the current position.This is attached with L because this is a long integer. Pointer position:This sets the pointer position in the file. Value pointer position 0 Beginning of file. 1 Current position 2 End of file
  • 60. Example OUTPUT: It depends on the content in the file.
  • 61. ftell() This function returns the current position of the file position pointer. The value is counted from the beginning of the file. Syntax long ftell(FILE *fp);
  • 62. rewind() This function is used to move the file pointer to the beginning of the file. This function is useful when we open file for update. Syntax: rewind(FILE *fp); Here, fp is file pointer of type FILE
  • 63. C Pre-processor Directives The C Preprocessor is not a part of the compiler but is a separate step in the compilation process. In simple terms, a C Preprocessor is just a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. We will refer to the C Preprocessor as CPP. All preprocessor commands begin with a hash symbol (#). It must be the first nonblank character, and for readability, a preprocessor directive should begin in the first column. The following section lists down all the important preprocessor directives –
  • 66. Predefined Macros ANSI C defines a number of macros. Although each one is available for use in programming, the predefined macros should not be directly modified
  • 68. Preprocessor Operators The Macro Continuation () Operator A macro is normally confined to a single line. The macro continuation operator () is used to continue a macro that is too long for a single line. For example − #define message_for(a, b) printf(#a " and " #b ": We love you!n")
  • 69. The Stringize (#) Operator #include <stdio.h> #define message_for(a, b) printf(#a " and " #b ": We love you!n") int main(void) { message_for(Carole, Debra); return 0; } Output Carole and Debra: We love you! The stringize or number-sign operator ( '#' ), when used within a macro definition, converts a macro parameter into a string constant. This operator may be used only in a macro having a specified argument or parameter list. For example –
  • 70. The Token Pasting (##) Operator #include <stdio.h> #define tokenpaster(n) printf ("token" #n " = %d", token##n) int main(void) { int token34 = 40; tokenpaster(34); return 0; } Output token34 = 40 The token-pasting operator (##) within a macro definition combines two arguments. It permits two separate tokens in the macro definition to be joined into a single token. For example –
  • 71. The Defined() Operator #include <stdio.h> #if !defined (MESSAGE) #define MESSAGE "You wish!" #endif int main(void) { printf("Here is the message: %sn", MESSAGE); return 0; } Output Here is the message: You wish! The preprocessor defined operator is used in constant expressions to determine if an identifier is defined using #define. If the specified identifier is defined, the value is true (non-zero). If the symbol is not defined, the value is false (zero). The defined operator is specified as follows –
  • 72. Parameterized Macros One of the powerful functions of the CPP is the ability to simulate functions using parameterized macros. For example, we might have some code to square a number as follows − int square(int x) { return x * x; } We can rewrite above the code using a macro as follows − #define square(x) ((x) * (x))
  • 73. Types There are 4 main types of preprocessor directives: Macros File Inclusion Conditional Compilation Other directives
  • 74. Macros Macros are a piece of code in a program which is given some name. Whenever this name is encountered by the compiler the compiler replaces the name with the actual piece of code. The „#define‟ directive is used to define a macro. Let us now understand the macro definition with the help of a program:
  • 75. Macros with arguments We can also pass arguments to macros. Macros defined with arguments works similarly as functions. Let us understand this with a program:
  • 76. File Inclusion Header File or Standard files: These files contains definition of pre- defined functions like printf(), scanf() etc. These files must be included for working with these functions. Different function are declared in different header files. For example standard I/O functions are in „iostream‟ file whereas functions which perform string operations are in „string‟ file. Syntax: #include<file_name> where file_name is the name of file to be included. The „<„ and „>‟ brackets tells the compiler to look for the file in standard directory. user defined files: When a program becomes very large, it is good practice to divide it into smaller files and include whenever needed. These types of files are user defined files. These files can be included as: #include"filename" This type of preprocessor directive tells the compiler to include a file in the source code program. There are two types of files which can be included by the user in the program:
  • 77. Conditional Compilation Syntax: #ifdef macro_name statement1; statement2; statement3; . . . statementN; #endif If the macro with name as „macroname„ is defined then the block of statements will execute normally but if it is not defined, the compiler will simply skip this block of statements. Conditional Compilation directives are type of directives which helps to compile a specific portion of the program or to skip compilation of some specific part of the program based on some conditions. This can be done with the help of two preprocessing commands „ifdef„ and „endif„.
  • 78. Other directives #undef Directive: The #undef directive is used to undefine an existing macro. This directive works as: #undef LIMIT Using this statement will undefine the existing macro LIMIT. After this statement every “#ifdef LIMIT” statement will evaluate to false. #pragma Directive: This directive is a special purpose directive and is used to turn on or off some features. This type of directives are compiler-specific, i.e., they vary from compiler to compiler. Some of the #pragma directives are discussed below: #pragma startup and #pragma exit: These directives helps us to specify the functions that are needed to run before program startup( before the control passes to main()) and just before program exit (just before the control returns from main()). Apart from the above directives there are two more directives which are not commonly used. These are:
  • 80. Cont… #pragma warn Directive: This directive is used to hide the warning message which are displayed during compilation. We can hide the warnings as shown below: #pragma warn -rvl: This directive hides those warning which are raised when a function which is supposed to return a value does not returns a value. #pragma warn -par: This directive hides those warning which are raised when a function does not uses the parameters passed to it. #pragma warn -rch: This directive hides those warning which are raised when a code is unreachable. For example: any code written after the return statement in a function is unreachable.