0% found this document useful (0 votes)
25 views

Unit 5

Uploaded by

elitetube1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Unit 5

Uploaded by

elitetube1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

U23CSTC01–Programming In C Regulation 2023

UNIT V

UNIONS AND FILES


Union Introduction - Programs Using Structures and Unions – Introduction to File - File Operations -
File Input and Output Functions - Random Access to Files - File System Functions - Command Line
Arguments- Storage Classes - Pre-Processor Directives- Dynamic Memory Functions.
U23CSTC01–Programming In C Regulation 2023

UNION
A union is a special data type available in C to store different data types in the same memory
location. We can define a union with many members, but only one member can contain a value at a
time. Unions provide an efficient way of using the same memory location for multi-purpose.

DEFINITION
Defining a union, is very similar as like defining structure but keyword union is used. The
union statement defines a new data type, with more than one member for your program.

Syntax:

union

member definition;
member definition;

...

member definition;

} [one or more union variables];

Each member definition is a normal variable definition, such as int i; or float f; or any other
valid variable definition. At the end of the union's definition, before the final semicolon, union
variables are declared.
Example:
union sample
{
int marks;
float avg;
char grade;
};
Now, a variable of sample type can store an integer, a floating-point number, or a string of
U23CSTC01–Programming In C Regulation 2023

characters. This means that a single variable ie. same memory location can be used to store multiple
types of data. We can use any built-in or user defined data types inside a union based on requirement.

Memory allocation
In structure
struct student
{
int rollno;
char gender;
float marks;
};

In union
union student
{
int rollno;
char gender;
float marks;
};
U23CSTC01–Programming In C Regulation 2023

INITIALIZING THE UNION

The initialization of a union is the initialization of its members by simply assigning the value to it.

var1.member1 = some_value;

One important thing to note here is that only one member can contain some value at a given
instance of time.
ACCESSING UNION MEMBERS
To access any member of a union, the member access operator (.) is used. The union keyword to define
variables of union type. Following is the example to explain usage of union:
#include <stdio.h>
#include <conio.h>
union number
{
int n1; float n2;
}union number x;
void main()
{
clrscr() ;
printf("Enter the value of n1: ");
scanf("%d", &x.n1);
printf("Value of n1 =%d", x.n1);
printf("\nEnter the value of n2: ");
scanf("%d", &x.n2);
printf("Value of n2 = %d\n",x.n2);
}
Output:
U23CSTC01–Programming In C Regulation 2023

Enter the value of n1:10


Value of n1 =10
Enter the value of n2:20.5
Value of n2 =20.50000

FILE HANDLING
Definition of Files
“A file is a collection of related information that is permanently stored onthe disk and allows
us to access and alter the information whenever necessary.”
Need of Files:
In order to efficiently analyze all the data that has been collected from differentsources.
Storing data as files in permanent storage devices like hard disk so to make availability of data for
future use.
Definition:
A file is a collection of related data stored on a secondary storage device likehard disk. Every
file contains data that is organized in hierarchy as fields, records, and databases Stored as sequence of
bytes, logically contiguous (may not be physicallycontiguous on disk).
Streams
Stream is a Sequence of data bytes, which is used to read and write data toa file. A Stream acts
as an interface between a program and an input/outputDevice.
Input and Output stream:
Input streams get the data from different input devices such as keyboardand mouse and provide
input data to the program.
Output Streams obtain data from the program and write that on different
Output Devices such as Memory or print them on the Screen.
Buffer in files:
A buffer is a block of memory that is used for temporary storage of data that has to be read from or
written to a file. The buffer acts as an interface between the stream (which is character-oriented) and
the disk hardware (which is block oriented).
U23CSTC01–Programming In C Regulation 2023

Field: Single unit in the file


Record :It is logical group of data fields that comprise a single row ofinformation, which describes the
characteristics of an item.
Directory: It is a collection of related files.

Standard streams available in C language


standard input (stdin) - Standard input stream from which programreceives its data
standard output (stdout) -Standard output stream where a programwrites its output data
standard error (stderr)- Standard error an output stream used byprograms to report error messages.
Types of files
Text file or ASCII text file: It is a stream of characters that can beprocessed sequentially and in
forward direction only.
Binary file: It is collection of bytes.
Sequential File: Data is stored sequentially, to read the last record of the file, we need to traverse all
the previous records before it. Eg: files onmagnetic tapes.
Random Access File: Data can be accessed and modified randomly. We can read any record directly.
Eg: files on disks.
U23CSTC01–Programming In C Regulation 2023

File attributes.
The various file attributes are:
Filename - String of characters to store the name of files.
File Position -Pointer that points the position at which next read and writeoperation to be performed.
File Structure -It indicates whether file is text or binary file
File Access Methods- Indicates whether file can be accessed sequentially orrandomly
Attributes flag: Specifies that hidden or read-only or archive file.

File operations.
Creating a new file
Opening an existing file
Reading from a file
Writing to a file
Moving to a specific location in a file (seek)
Closing a file

DEFINING AND OPENING A FILE

FILE *fptr;

General form of declaring a file.


FILE is a defined Data type. FILE should be compulsorily written in Uppercase.
The pointer fptr is referred to as the stream pointer. This pointer contains all the information about the
file. Before performing any Input/Output operation in a file, it must be opened by the program.
Opening a file established a connection between the file and the program in which the file is opened.
Oncethe file has been opened, the program can perform Input/Output process on the file.
While opening the file, the following should be specified.
 Name of the file.
 Purpose of opening the file (i.e., for reading or writing or appending etc.,)
fopen() function is used to open a file. It accepts two arguments, first argument is the name of the
file, and the second argument is the mode inwhich the file is to be opened.
U23CSTC01–Programming In C Regulation 2023

Syntax:

FILE *fptr;
fptr = fopen(“filename”, ”mode”);

Description: filename – Assigned as an identifier to the filefptr – Acts as a pointer to the data
FILE - defined Data type.
Example: fptr = fopen(“computer”, ”r”); //*r- opens the file in readmode*//

File Type Modes of FileOperations

“r” open the file for read only.

“w” open the file for writing only.

“a” open the file for appending data to it.

r+ Read and write

w+ Write and read

“a+” Opens existing file for reading and writing.

“rb” open the binary file for read only.

“wb” open the binary file for writing only.

“r+b” Opens a binary file for read and write operations.


or “rb+”

“w+b” Creates and opens binary file for read and writeoperations.
or “wb+”

“a+b” Opens a binary file for for read and write operations.
or “ab+”

CLOSING A FILE
A file is closed when no more Input/Output operations is to be performed on it.Closing a file is
U23CSTC01–Programming In C Regulation 2023

carried out by using the fclose() library functions.


Syntax:

fclose(fptr);

Example:
FILE *book;
book = fopen(“computer”, ”r”);.
fclose(book);

Example Program 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 ) ;
}

Output
The content of the file will be printed.

Example program to write data to a text file and to read it


#include<stdio.>
#include<conio.>
U23CSTC01–Programming In C Regulation 2023

int main( )
{
FILE *fp; int rno , i;
float avg;
char name[20] , filename[15];
clrscr();
printf("\nEnter the filename:\n");
scanf("%s",filename);
fp=fopen(filename,"w");
for(i=1;i<=3;i++)
{
printf("Enter rno,name,average of student no%d:",i);
scanf("%d %s %f",&rno,name,&avg);
fprintf(fp,"%d %s %f\n",rno,name,avg);
}
fclose(fp);
fp=fopen ( filename, "r" );
printf(“The Students details”);
for(i=1;i<=3;i++)
{
fscanf(fp,"%d %s %f",&rno,name,&avg);
printf("\n%d %s %f",rno,name,avg);
}
fclose(fp);
getch();
return 0;
}

Output:
Enter the filename:
test.txt
Enter rno,name,average of student no:1 101ram 75
U23CSTC01–Programming In C Regulation 2023

Enter rno,name,average of student no:2 102Raj 79.4


Enter rno,name,average of student no:3 103Rahul 92.3
The Students details 101 ram 75.000000
102 Raj 79.400002
103 Rahul 92.300003

FILE INPUT AND OUTPUT FUNCTIONS


There are eight operations on files. They are
 putc()
 getc()
 getw()
 putw()
 fscanf()
 fread()
 fprintf()
 fwrite()
1. SINGLE CHARACTER INPUT/OUTPUT FUNCTIONS FOR FILES

Once a file is opened, an Input/Output operations is performed on file, source of thefunctions which
facilitate single character Input/Output for file getc() & putc().
The single character Input function fgetc() receives a single argument, a file pointer for the file from
which a character is read.

Single character input function - putc()


This function operates on file that is copied in writing mode, which writes asingle character to the file.
Syntax: putc(c,fptr);
Single character output function - getc()
This function operates on file that is opened in reading mode. Reads a singlecharacter from the
file.
Syntax: getc(fptr);
Reads character from file pointed by file pointer fp and displays on it screen. Now file pointer moves
by one character position for every getc() function and returns EOF (end-of-file). EOF is a constant
U23CSTC01–Programming In C Regulation 2023

that indicates the end-of-file reached on afile. To get character from a file terminating character (^z)
is entered.
Example: WRITING TO AND READING FROM A FILE.
#include <stdio.h>main()
{
FILE *f1;
char c;
printf("Data Input\n\n");
/* Open the file INPUT */
f1 = fopen("INPUT", "w");
/* Get a character from keyboard */
while((c=getchar()) != EOF)
/* Write a character to INPUT */
putc(c,f1);
/* Close the file INPUT */
fclose(f1);
printf("\nData Output\n\n");
/* Reopen the file INPUT */
f1 = fopen("INPUT","r");
/* Read a character from INPUT*/
while((c=getc(f1)) != EOF)
/* Display a character on screen */
printf("%c",c);
/* Close the file INPUT */
fclose(f1);
}
Output:

Data Input
This is a program to test the file handling features on this system^Z
Data Output
This is a program to test the file handling features on this system
U23CSTC01–Programming In C Regulation 2023

ERROR HANDLING WHILE READING AND WRITING FILES

The incorrect reading and writing situation are listed below:

 Reading a file beyond the end-of-file (EOF).


 Accessing a file that has not been opened.
 Opening a file with the invalid filename.
 Reading a file that is opened in write mode.
 Writing on a file that is opened in read mode.
 Tyring to write to a file which is write-protected one.
 Closing a file that is not opened.

The feof() function:


The feof() function is used to check whether the file pointer is at the end-of- file or not. It takes
the file pointer as the argument and returns non-zero if the file pointer is at the end-of- file. Otherwise
it returns zero.
The ferror() function:

The ferror() function reports the status of the file indicated. It also takes a FILE pointer as its only
argument and returns a non zero integer if an error has been detected up to that point, during
processing. It returns zero otherwise.
RANDOM ACCESS TO FILES

Sequential Files are generally used in cases where the program processes the data in a
sequential fashion.
Eg: counting words in a text file
Random Access File functions
To access a particular part of a file randomly and not in reading the other parts. This is done by using
the I/O library functions, namely
 fseek()
U23CSTC01–Programming In C Regulation 2023

 ftell()
 rewind()
fseek() FUNCTION

The fseek() function allows us to read from or write to any point in the stream of bytes opened by
using the fopen() function. It is used to move the position of the file pointer to the desired location in
the file.

Syntax fseek(fptr, offset, position)

Description fptr – file pointer of the file to be accessed.

offset – is a negative or positive number or a variable of long integer data


type to reposition the file pointer towards the backward or forward
direction from the location specified by position.
position – Current position of the file pointer.
Example: Beginning

fseek(fptr,5L,0)
;

5 byte

ftell() FUNCTION
Function returns the current position of the file pointer in the file.

Syntax

long int ftell(fptr);


U23CSTC01–Programming In C Regulation 2023

Example

a = ftell(fptr); Returns the size of thefile in bytes


to the variable a.

rewind() FUNCTION
Function resets the file pointer to the beginning of the file.

Syntax
rewind(fptr);

Example Program that uses the functions ftell and fseek.

A program employing ftell and fseek functions is shown. We have created a file RANDOM with the
following contents:
Position ----> 0 1 2 25
Character
stored ----> A B C Z
(ILLUSTRATION OF fseek & ftell FUNCTIONS)
#include <stdio.h>
main()
{

FILE *fp;
long n;
char c;
fp = fopen("RANDOM", "w");
while((c = getchar()) != EOF)
putc(c,fp);
printf("No. of characters entered = %ld\n", ftell(fp));
fclose(fp);
U23CSTC01–Programming In C Regulation 2023

fp = fopen("RANDOM","r");
n = 0L;
while(feof(fp) == 0)
{
fseek(fp, n, 0);/* Position to (n+1)th character*/
printf("Position of %c is %ld\n", getc(fp),ftell(fp));
n = n+5L;
}
putchar('\n');
fseek(fp,-1L,2); /* Position to the last character */
do
{
putchar(getc(fp));
}

while(!fseek(fp,-2L,1));
fclose(fp);
}

Output:
ABCDEFGHIJKLMNOPQRSTUVWXYZ^Z
No. of characters entered = 26 Position of A is 0
Position of F is 5 Position of K is 10 Position of P is 15 Position of U is 20 Position of Z is 25 Position
of is 30
ZYXWVUTSRQPONMLKJIHGFEDCBA

RANDOM ACCESSING FILES


Random accessing of files in C language can be done with the help of the following functions −
ftell ( )
rewind ( )
fseek ( )
ftell ( )
U23CSTC01–Programming In C Regulation 2023

It returns the current position of the file ptr.


The syntax is as follows −
int n = ftell (file pointer)
For example,
FILE *fp;
int n;

n = ftell (fp);
Note − ftell ( ) is used for counting the number of characters which are entered into a file.
rewind ( )
It makes file ptr move to beginning of the file.
The syntax is as follows −
rewind (file pointer);
For example,
FILE *fp;

rewind (fp);
n = ftell (fp);
printf ("%d”, n);
Output
The output is as follows −
0 (always).
fseek ( )
It is to make the file pntr point to a particular location in a file.
The syntax is as follows −
fseek(file pointer, offset, position);
Offset
The no of positions to be moved while reading or writing.
If can be either negative (or) positive.
U23CSTC01–Programming In C Regulation 2023

Positive - forward direction.


Negative – backward direction.
Position
It can have three values, which are as follows −
0 – Beginning of the file.
1 – Current position.
2 – End of the file.
Example
fseek (fp,0,2) - fp moved 0 bytes forward from the end of the file.
fseek (fp, 0, 0) – fp moved 0 bytes forward from beginning of the file
fseek (fp, m, 0) – fp moved m bytes forward from the beginning of the file.
fseek (fp, -m, 2) – fp moved m bytes backward from the end of the file.
Errors
The errors related to fseek () function are as follows −
fseek (fp, -m, 0);
fseek(fp, +m, 2);

COMMAND LINE ARGUMENTS


An executable program that performs a specific task for operating system is called as
command.The commands are issued from the prompt of operating system, some arguments are
associated with the commands, and hence these arguments are called as command line arguments.
The main() function receives two arguments and they are
 argc
 argv

Argument argc
An argument argc counts total number of arguments passed from command prompt. It returns a value
which is equal to total number of arguments passed through main().
Argument argv
It is a pointer to an array of character strings which contains names of arguments. Each word is an
argument.
int main ( int argc, char *argv[] )
U23CSTC01–Programming In C Regulation 2023

Command line argument is a parameter supplied to a program when the program is invoked.
This parameter represents filename of the program that should process.
In general, execution of C program starts from main() function. It has two arguments like argc
and argv. The argc is an argument counter that counts the number of arguments on the command line.
The argv is an argument vector. It represents an array of character pointer that point to command line
arguments.
The size of the array will be equal to the value of argc. Information contained in command line
is passed to program through these arguments whenever main is called. The first parameter in
command line is program name. Here argv[0] represents the program name.
To access command line arguments, declare the main function and parameter as

main(int argc, char *argv[ ])


{
……..
}

Program to Sum of integers using command line arguments


#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void main(int argc , char *argv[])
{
int i,sum=0;
clrscr();
printf("\n\tSUM OF INTEGERS USING COMMAND LINE ARGUMENT");
printf("\n\t*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*");
if(argc<3)
{
printf("\nAtleast Type 2 Numbers");
exit(1);
}
U23CSTC01–Programming In C Regulation 2023

printf("\nThe sum is : ");


for(i=1;i<argc;i++)
sum = sum + atoi(argv[i]);
printf("%d",sum);
}
Program to copy the content of one file to another file using command line arguments
#include<stdio.h>
#include<stdlib.h>
int main(int argc,char *argv[])
FILE *fp1,*fp2;
int i,ch;
if(argc!=3)
{
printf("Program parameter missing");
exit(0);
}
fp1=fopen(argv[1],"r");
fp2=fopen(argv[2],"a");
while((ch=getc(fp1))!=EOF) putc(ch,fp2);
printf("file %s is successfully copied",argv[1]);
Return(0);
}
STORAGE CLASSES:
C Storage Classes are used to describe the features of a variable/function. These features
basically include the scope, visibility, and lifetime which help us to trace the existence of a particular
variable during the runtime of a program.
C language uses 4 storage classes, namely:
U23CSTC01–Programming In C Regulation 2023

1. auto
This is the default storage class for all the variables declared inside a function or a block.
Hence, the keyword auto is rarely used while writing programs in C language. Auto variables can be
only accessed within the block/function they have been declared and not outside them (which defines
their scope). Of course, these can be accessed within nested blocks within the parent block/function in
which the auto variable was declared.
However, they can be accessed outside their scope as well using the concept of pointers given
here by pointing to the very exact memory location where the variables reside. They are assigned a
garbage value by default whenever they are declared.
2. extern
Extern storage class simply tells us that the variable is defined elsewhere and not within the
same block where it is used. Basically, the value is assigned to it in a different block and this can be
overwritten/changed in a different block as well. So an extern variable is nothing but a global variable
initialized with a legal value where it is declared in order to be used elsewhere. It can be accessed
within any function/block.
Also, a normal global variable can be made extern as well by placing the ‘extern’ keyword
before its declaration/definition in any function/block. This basically signifies that we are not
initializing a new variable but instead, we are using/accessing the global variable only. The main
U23CSTC01–Programming In C Regulation 2023

purpose of using extern variables is that they can be accessed between two different files which are
part of a large program.
3. static
This storage class is used to declare static variables which are popularly used while writing
programs in C language. Static variables have the property of preserving their value even after they are
out of their scope! Hence, static variables preserve the value of their last use in their scope. So we can
say that they are initialized only once and exist till the termination of the program. Thus, no new
memory is allocated because they are not re-declared.
Their scope is local to the function to which they were defined. Global static variables can be
accessed anywhere in the program. By default, they are assigned the value 0 by the compiler.
4. register
This storage class declares register variables that have the same functionality as that of the auto
variables. The only difference is that the compiler tries to store these variables in the register of the
microprocessor if a free register is available. This makes the use of register variables to be much faster
than that of the variables stored in the memory during the runtime of the program.
If a free registration is not available, these are then stored in the memory only. Usually, a few
variables which are to be accessed very frequently in a program are declared with the register keyword
which improves the running time of the program. An important and interesting point to be noted here
is that we cannot obtain the address of a register variable using pointers.
Syntax
To specify the storage class for a variable, the following syntax is to be followed:

storage_class var_data_type var_name;

Example
Functions follow the same syntax as given above for variables. Have a look at the following C
example for further clarification:
// A C program to demonstrate different storage // classes
#include <stdio.h>
int x;
void autoStorageClass()
{
printf("\nDemonstrating auto class\n\n");
U23CSTC01–Programming In C Regulation 2023

auto int a = 32;


printf("Value of the variable 'a'"" declared as auto: %d\n", a);
printf(" ");
}
void registerStorageClass()
{
printf("\nDemonstrating register class\n\n");
register char b = 'G';
printf("Value of the variable 'b'"" declared as register: %d\n", b);
printf(" ");
}
void externStorageClass()
{
printf("\nDemonstrating extern class\n\n");
extern int x;
printf("Value of the variable 'x'"" declared as extern: %d\n", x);
x = 2;
printf("Modified value of the variable 'x'"" declared as extern: %d\n", x);
printf(" ");
}
void staticStorageClass()
{
int i = 0;

printf("\nDemonstrating static class\n\n");


printf("Declaring 'y' as static inside the loop.\n"
"But this declaration will occur only"
" once as 'y' is static.\n"
"If not, then every time the value of 'y' "
"will be the declared value 5"
" as in the case of variable 'p'\n");
printf("\nLoop started:\n");
U23CSTC01–Programming In C Regulation 2023

for (i = 1; i < 5; i++)


{
static int y = 5;
int p = 10;
y++;
p++;
printf("\nThe value of 'y', "
"declared as static, in %d "
"iteration is %d\n", i, y);
printf("The value of non-static variable 'p', "
"in %d iteration is %d\n", i, p);
}
printf("\nLoop ended:\n");
printf(" ");
}
int main()
{
printf("A program to demonstrate"" Storage Classes in C\n\n");
autoStorageClass();
registerStorageClass();
externStorageClass();
staticStorageClass();

printf("\n\nStorage Classes demonstrated");


return 0;
}
U23CSTC01–Programming In C Regulation 2023

PREPROCESSOR
Definition
The Preprocessor, as the name implies, is a program that processes the source code before it
passes through the complier. This is known as preprocessor.

Important Points
It operates under the control of preprocessor command lines or directives. Preprocessor
directives are placed in the source program before the main line. Before the source code passes through
the compiler, it is examined by the preprocessor for any preprocessor directives. Preprocessor
directives begin with the symbol # in column one and do not require a semicolon at the end.

Three Categories
 Macro substitution directives
 File Inclusion directives
 Compiler control directives (or) Conditional inclusion directives
U23CSTC01–Programming In C Regulation 2023

Macro Substitution Directive


It is also called as #define preprocessor directives. The working manner is, simply removes the
occurrences of the constant and replaces them using the expression
Syntax
The general form is

#define identifier string

Examples
Simple Macro Sub for Expressions
#define AREA 5 * 12.46
#define SIZE sizeof(int) * 7
#define TWO-PI 2.0 * 3.14
#define A (55 – 33)
#define B (55 + 33)

Simple Macro Sub for Creating C Sentences


#defineTEST if (x>y)
#defineAND
#definePRINT printf(“Success”);
Note: The above statements are consider as, TEST AND PRINT That will become
if (x>y) printf (“Success \n”);
Simple Macro Sub for Replacing Tokens
#define EQALS ==
#define AND OR || &&
#define NOT-EQUAL !=
#define
#define START {
#define END }
#define BLANK_LINE printf(“\n”);
#define INCREMENT ++
U23CSTC01–Programming In C Regulation 2023

Macros With Arguments


More complex and more useful form of replacement
#define identifier(f1,f2,…..,fn) string
No space between id and the left (
Subsequent occurrence of a macro with arguments is known as a macro call
When macro is called, the preprocessor substitutes replacing formal with actual parameters

A Simple Example of Macros With Arguments (MWA)


#define CUBE(x) (x*x*x)
volume = CUBE (side) // (side * side * side) volume = CUBE (a + b) would expand to volume = (a +
b * a + b * a + b)
Explanation:
#define CUBE (x) ( (x) * (x) * (x) )is a correct definition, which expands to volume = ((a +b) * (a + b)
* (a + b))

Program #include<stdio.h> #define PIE 3.14 main()


{
float r=3,area; area=2*r*PIE; printf(“%f”,area); getch();
}

File Inclusion Directive


This is achieved by #include “filename
or
#include <filename>
Example
#include <stdio.h> #include “TEST.C”

Compiler Control Directives (Or) Conditional Inclusion


These are the directives meant for controlling the compiler actions. C preprocessor offers a
feature known as conditional compilation, which can be used to switch off or on a particular line or
group of lines in a program.
Mostly #ifdef and #ifndef are used in these directives.
U23CSTC01–Programming In C Regulation 2023

Rules for defining Preprocessor


 Every preprocessor must start with # symbol.
 The preprocessor is always placed before main() function.
 The preprocessor cannot have termination with semicolon.
 There is no assignment operator in #define statement.
 The conditional macro must be terminated (#ifdef, #endif).

Predefined Macros
ANSI C defines a number of macros. Although each one is available for your use in
programming, the predefined macros should not be directly modified.

Macro Description

DATE The current date as a character literal in "MMM DD YYYY" format

TIME The current time as a character literal in "HH:MM:SS" format

FILE This contains the current filename as a string literal.

LINE This contains the current line number as a decimal constant.

STDC Defined as 1 when the compiler complies with the ANSI standard.

Example
#include <stdio.h>
main()
{
printf("File :%s\n", FILE; printf("Date :%s\n",DATE );
printf("Time :%s\n",TIME);
printf("Line :%d\n",LINE );
printf("ANSI :%d\n",STDC);
}

Note: The above program is saved in sample.c


U23CSTC01–Programming In C Regulation 2023

Output
File :C:\Users\Documents\sample.c Date :Aug 5 2015
Time :19:03:18
Line :7
ANSI :1

Miscellaneous Directives:
There are two more pre-processor directives, though they are not very commonly used.
They are #undef and #pragma
#undef
On some occasion, it may b desirable to cause a defined name to become „undefined‟. This can
be accomplished by means of the 3undef directive.
Eg: #undef PENTIUM would cause the definition of PENTUM to be removed from the system. All
subsequent #ifdef PENTUM statements became false.

#include<stdio.h>
#define height 100
void main()
{
printf (“First defined height value: %d”,height); #undef height
//undefined variable
#define height 700//redefining the same for new value
printf(“Height value after redefining %d”,height );
}

Output
First defined count value:100
U23CSTC01–Programming In C Regulation 2023

SL.N O PRAGMA COMMAND DESCRIPTION

#pragma startup
This directive executes function named
1.
“function_name_1”before starting of the program
<function_name_1>
This directive executes function named
#pragma exit
2. “function_name_2”before termination of
<function_name_2>
the program
If function doesn‟t return a value, then
3. #pragma warn-rvl
warnings are suppressed by this directive while compiling.

If function doesn‟t use passed function parameter, then


4. #pragma warm-par
warnings are suppressed.
If non-reachable code is written inside a
5. #pragma warn-rch
program, such warnings are suppressed by this directive.
Height value after redefining:700
#pragma
A special directive we can turn on or off certain features. Pragma vary from one compiles to another.
The following table shows list of programmer command

Example Program
#include<stdio.h>
int display();
#pragma startup display
#pragma exit display
int main()
{
printf("\nI am in main function");
return 0;
}
int display()
{
printf("\nI am in display function");
U23CSTC01–Programming In C Regulation 2023

return 0;
}
Output:
Enter the filename: test.txt
Enter rno,name,average of student no:1 101 ram 75
Enter rno,name,average of student no:2 102 raj 79.4
Enter rno,name,average of student no:3 103 rahul 92.3
The Students details 101 ram 75.000000
102 raj 79.400002
103 rahul 92.300003
DYNAMIC MEMORY FUNCTIONS.

Dynamic Memory Allocation refers to the process of allocating or deallocating memory blocks during
a program’s runtime. This is achieved through the use of four functions:
Method Description

malloc() Allocates a single block of requested memory.

calloc() Allocates multiple blocks of requested memory.

realloc() Reallocates the memory occupied by malloc() or calloc() functions.

free() Frees the dynamically allocated memory.

These functions are located in the <stdlib.h> header file. Dynamic memory allocation can also be
considered as a method of utilizing heap memory, where the size of variables or data structures (such
as arrays) can be changed during a program’s execution with the help of these library functions.
Now, Let us look at the definition, syntax and C example of each of the above-mentioned functions:
Malloc() Method
malloc() is a function in C that dynamically allocates a block of memory of a specified size (in
bytes) in the heap section of memory during the runtime of a C program. It can be found in
the <stdlib.h> header file.
Syntax
The syntax of malloc() function in C is shown below:

void *malloc(size_t size);


U23CSTC01–Programming In C Regulation 2023

 size is the size in bytes of the memory block to be allocated.


 malloc() returns a pointer to the first byte of the allocated memory block. If the memory
allocation fails, it returns a NULL pointer.
Calloc() Method
The calloc() function in C is used to dynamically allocate a contiguous block of memory in the
heap section. Unlike malloc(), calloc() is used to allocate multiple blocks of memory, typically to store
an array of elements.
Syntax
The syntax of calloc() function in C is shown below:

(cast-type*) calloc(n, size);

 cast-type is the type you want to cast the allocated memory to (for example, int* or float*)
 n is the number of blocks to be allocated
 size is the size of each block in bytes
Realloc() Method
realloc() is a function in C that allows you to change the size of a previously allocated memory
block. This function can be used to increase or decrease the size of a block of memory that was
previously allocated using either malloc() or calloc(). It can also be used to completely allocate or de-
allocate a memory block on its own.
Syntax
The syntax of realloc() function in C is shown below:

void *realloc(void *ptr, size_t size);

 ptr is a pointer to the memory block previously allocated using malloc() or calloc().
 size is the new size for the memory block, in bytes. The function returns a pointer to the newly
allocated memory block. If the reallocation fails, the function returns NULL.
Free() Method
The free() method in C is used to deallocate a memory block previously allocated
by malloc() or calloc() functions during the execution of the program. It frees up the occupied memory
so that it can be reused again.
Syntax
The syntax of free() function in C is shown below:

void free(void *ptr);


U23CSTC01–Programming In C Regulation 2023

 Here, ptr is a pointer to the memory block that needs to be deallocated.


Here’s an example of how to use free() to dynamically deallocate memory in C:

You might also like