[go: up one dir, main page]

0% found this document useful (0 votes)
43 views37 pages

Unit 4 Adv C

The document discusses file handling in C programming. It explains why file handling is needed, the different file operations like creating, opening, reading and writing to files. It also explains the different modes for opening files and provides examples to demonstrate writing and reading from text and binary files.

Uploaded by

Hardik Rathore
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)
43 views37 pages

Unit 4 Adv C

The document discusses file handling in C programming. It explains why file handling is needed, the different file operations like creating, opening, reading and writing to files. It also explains the different modes for opening files and provides examples to demonstrate writing and reading from text and binary files.

Uploaded by

Hardik Rathore
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/ 37

Unit-4th

Files and Preprocessor Directives

File Handling in C

In programming, we may require some specific input data to be generated several numbers of
times. Sometimes, it is not enough to only display the data on the console. The data to be displayed
may be very large, and only a limited amount of data can be displayed on the console, and since the
memory is volatile, it is impossible to recover the programmatically generated data again and
again. However, if we need to do so, we may store it onto the local file system which is volatile and
can be accessed every time. Here, comes the need of file handling in C.

File handling in C enables us to create, update, read, and delete the files stored on the local file
system through our C program. The following operations can be performed on a file.

Why do we need File Handling in C?


So far the operations using the C program are done on a prompt/terminal which is not stored
anywhere. The output is deleted when the program is closed. But in the software industry, most
programs are written to store the information fetched from the program. The use of file handling
is exactly what the situation calls for.
In order to understand why file handling is important, let us look at a few features of using files:
Application of file handling:-
● Reusability: The data stored in the file can be accessed, updated, and deleted anywhere and
anytime providing high reusability.
● Portability: Without losing any data, files can be transferred to another in the computer system.
The risk of flawed coding is minimized with this feature.
● Efficient: A large amount of input may be required for some programs. File handling allows you
to easily access a part of a file using few instructions which saves a lot of time and reduces the
chance of errors.
● Storage Capacity: Files allow you to store a large amount of data without having to worry about
storing everything simultaneously in a program.

Operation of file handling:-File handling in C enables us to create, update, read, and delete the files
stored on the local file system through our C program. The following operations can be performed
on a file.

o Creation of the new file


o Opening an existing file
o Reading from the file
o Writing to the file
o Deleting the file

File Operations

In C, you can perform four major operations on files, either text or binary:

1. Creating a new file

2. Opening an existing file

3. Closing a file

4. Reading from and writing information to a file

Working with files

When working with files, you need to declare a pointer of type file. This declaration is needed for
communication between the file and the program.

FILE *fptr;

Opening a file - for creation and edit

Opening a file is performed using the fopen() function defined in the stdio.h header file.
The syntax for opening a file in standard I/O is:

ptr = fopen("fileopen","mode");

For example,

fopen("E:\\cprogram\\newprogram.txt","w");

fopen("E:\\cprogram\\oldprogram.bin","rb");

● Let's suppose the file newprogram.txt doesn't exist in the location E:\cprogram. The first function
creates a new file named newprogram.txt and opens it for writing as per the mode 'w'.
The writing mode allows you to create and edit (overwrite) the contents of the file.
● Now let's suppose the second binary file oldprogram.bin exists in the location E:\cprogram. The
second function opens the existing file for reading in binary mode 'rb'.
The reading mode only allows you to read the file, you cannot write into the file.
Opening Modes in Standard I/O

M During
Meaning of Mode
ode Inexistence of file

If the file does


r Open for reading. not exist, fopen() returns
NULL.

If the file does


R Open for reading
not exist, fopen() returns
b in binary mode.
NULL.

If the file exists,


its contents are
w Open for writing. overwritten.
If the file does not exist,
it will be created.

If the file exists,


its contents are
W Open for writing
overwritten.
b in binary mode.
If the file does not exist,
it will be created.

Open for append. If the file does


a Data is added to the end not exist, it will be
of the file. created.

If the file does


A
Open for append not exist, it will be
b
in binary mode. created.
Opening Modes in Standard I/O

M During
Meaning of Mode
ode Inexistence of file

Data is added to the end


of the file.

If the file does


r Open for both
not exist, fopen() returns
+ reading and writing.
NULL.

Open for both If the file does


r
reading and writing in not exist, fopen() returns
b+
binary mode. NULL.

If the file exists,


its contents are
w Open for both
overwritten.
+ reading and writing.
If the file does not exist,
it will be created.

If the file exists,


Open for both its contents are
w
reading and writing in overwritten.
b+
binary mode. If the file does not exist,
it will be created.

If the file does


a Open for both
not exist, it will be
+ reading and appending.
created.
Opening Modes in Standard I/O

M During
Meaning of Mode
ode Inexistence of file

Open for both If the file does


a
reading and appending in not exist, it will be
b+
binary mode. created.

Closing a File

The file (both text and binary) should be closed after reading/writing

Closing a file is performed using the fclose() function.

fclose(fptr);

Here, fptr is a file pointer associated with the file to be closed.

Reading and writing to a text file

For reading and writing to a text file, we use the functions fprintf() and fscanf().
They are just the file versions of printf() and scanf(). The only difference is
that fprintf() and fscanf() expects a pointer to the structure FILE.

Example 1: Write to a text file

#include<stdio.h>
#include<stdlib.h>

intmain()
{
int num;
FILE *fptr;

// use appropriate location if you are using MacOS or Linux


fptr = fopen("C:\\program.txt","w");

if(fptr == NULL)
{
printf("Error!");
exit(1);
}

printf("Enter num: ");


scanf("%d",&num);

fprintf(fptr,"%d",num);
fclose(fptr);

return0;
}

This program takes a number from the user and stores in the file program.txt.
After you compile and run this program, you can see a text file program.txt created in C drive of
your computer. When you open the file, you can see the integer you entered.

Example 2: Read from a text file

#include<stdio.h>
#include<stdlib.h>

intmain()
{
int num;
FILE *fptr;

if ((fptr = fopen("C:\\program.txt","r")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}
fscanf(fptr,"%d", &num);

printf("Value of n=%d", num);


fclose(fptr);

return0;
}

This program reads the integer present in the program.txt file and prints it onto the screen.
If you successfully created the file from Example 1, running this program will get you the integer
you entered.
Other functions like fgetchar(), fputc() etc. can be used in a similar way.

Reading and writing to a binary file

Functions fread() and fwrite() are used for reading from and writing to a file on the disk
respectively in case of binary files.

Writing to a binary file

To write into a binary file, you need to use the fwrite() function. The functions take four
arguments:
1. address of data to be written in the disk

2. size of data to be written in the disk

3. number of such type of data

4. pointer to the file where you want to write.

fwrite(addressData, sizeData, numbersData, pointerToFile);

Example 3: Write to a binary file using fwrite()

#include<stdio.h>
#include<stdlib.h>

structthreeNum
{
int n1, n2, n3;
};

intmain()
{
int n;
structthreeNumnum;
FILE *fptr;

if ((fptr = fopen("C:\\program.bin","wb")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}

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


{
num.n1 = n;
num.n2 = 5*n;
num.n3 = 5*n + 1;
fwrite(&num, sizeof(struct threeNum), 1, fptr);
}
fclose(fptr);

return0;
}

In this program, we create a new file program.bin in the C drive.


We declare a structure threeNum with three numbers - n1, n2 and n3, and define it in the main
function as num.
Now, inside the for loop, we store the value into the file using fwrite().
The first parameter takes the address of num and the second parameter takes the size of the
structure threeNum.
Since we're only inserting one instance of num, the third parameter is 1. And, the last
parameter *fptr points to the file we're storing the data.
Finally, we close the file.

Reading from a binary file

Function fread() also take 4 arguments similar to the fwrite() function as above.
fread(addressData, sizeData, numbersData, pointerToFile);

Example 4: Read from a binary file using fread()

#include<stdio.h>
#include<stdlib.h>

structthreeNum
{
int n1, n2, n3;
};

intmain()
{
int n;
structthreeNumnum;
FILE *fptr;

if ((fptr = fopen("C:\\program.bin","rb")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}

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


{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3);
}
fclose(fptr);

return0;
}

In this program, you read the same file program.bin and loop through the records one by one.
In simple terms, you read one threeNum record of threeNum size from the file pointed
by *fptr into the structure num.
You'll get the same records you inserted in Example 3.
Getting data using fseek()

If you have many records inside a file and need to access a record at a specific position, you need
to loop through all the records before it to get the record.

This will waste a lot of memory and operation time. An easier way to get to the required data can
be achieved using fseek().
As the name suggests, fseek() seeks the cursor to the given record in the file.

Syntax of fseek()

fseek(FILE * stream, longint offset, int whence);

The first parameter stream is the pointer to the file. The second parameter is the position of the
record to be found, and the third parameter specifies the location where the offset starts.

Different whence in fseek()

When
Meaning
ce

SEEK Starts the offset from the beginning of the


_SET file.

SEEK
Starts the offset from the end of the file.
_END

SEEK Starts the offset from the current location


_CUR of the cursor in the file.
Example 5: fseek()

#include<stdio.h>
#include<stdlib.h>

structthreeNum
{
int n1, n2, n3;
};

intmain()
{
int n;
structthreeNumnum;
FILE *fptr;

if ((fptr = fopen("C:\\program.bin","rb")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}

// Moves the cursor to the end of the file


fseek(fptr, -sizeof(struct threeNum), SEEK_END);

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


{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3);
fseek(fptr, -2*sizeof(struct threeNum), SEEK_CUR);
}
fclose(fptr);

return0;
}

This program will start reading the records from the file program.bin in the reverse order (last to
first) and prints it.
Types of Files

When dealing with files, there are two types of files you should know about:

1. Text files

2. Binary files
1. Text files

Text files are the normal .txt files. You can easily create text files using any simple text editors
such as Notepad.
When you open those files, you'll see all the contents within the file as plain text. You can easily
edit or delete the contents.

They take minimum effort to maintain, are easily readable, and provide the least security and takes
bigger storage space.

2. Binary files

Binary files are mostly the .bin files in your computer.


Instead of storing data in plain text, they store it in the binary form (0's and 1's).

They can hold a higher amount of data, are not readable easily, and provides better security than
text files.

o Mode of File handling:-


o We can use one of the following modes in the fopen() function.

Mode Description

R opens a text file in read mode

W opens a text file in write mode

A opens a text file in append mode

r+ opens a text file in read and write mode

w+ opens a text file in read and write mode

a+ opens a text file in read and write mode

Rb opens a binary file in read mode

Wb opens a binary file in write mode

Ab opens a binary file in append mode

rb+ opens a binary file in read and write mode

wb+ opens a binary file in read and write mode

ab+ opens a binary file in read and write mode


o
o The fopen function works in the following way.

o Firstly, It searches the file to be opened.


o Then, it loads the file from the disk and place it into the buffer. The buffer is used to
provide efficiency for the read operations.
o It sets up a character pointer which points to the first character of the file.

Consider the following example which opens a file in write mode.

1. #include<stdio.h>
2. void main( )
3. {
4. FILE *fp ;
5. char ch ;
6. fp = fopen("file_handle.c","r") ;
7. while ( 1 )
8. {
9. ch = fgetc ( fp ) ;
10. if ( ch == EOF )
11. break ;
12. printf("%c",ch) ;
13. }
14. fclose (fp ) ;
15. }

Output

The content of the file will be printed.

#include;
void main( )
{
FILE *fp; // file pointer
char ch;
fp = fopen("file_handle.c","r");
while ( 1 )
{
ch = fgetc ( fp ); //Each character of the file is read and stored in the character file.
if ( ch == EOF )
break;
printf("%c",ch);
}
fclose (fp );
}
Closing File: fclose()

The fclose() function is used to close a file. The file must be closed after performing all the
operations on it. The syntax of fclose() function is given below:

1. int fclose( FILE *fp );


C fprintf() and fscanf()

Writing File : fprintf() function

The fprintf() function is used to write set of characters into file. It sends formatted output to a
stream.

Syntax:

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


1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. fp = fopen("file.txt", "w");//opening file
5. fprintf(fp, "Hello file by fprintf...\n");//writing data into file
6. fclose(fp);//closing file
7. }

Reading File : fscanf() function

The fscanf() function is used to read set of characters from file. It reads a word from the file and
returns EOF at the end of file.

Syntax:

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

Example:

1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. char buff[255];//creating char array to store data of file
5. fp = fopen("file.txt", "r");
6. while(fscanf(fp, "%s", buff)!=EOF){
7. printf("%s ", buff );
8. }
9. fclose(fp);
10. }

Output:

Hello file by fprintf...

C File Example: Storing employee information

Let's see a file handling example to store employee information as entered by user from console.
We are going to store id, name and salary of the employee.

1. #include <stdio.h>
2. void main()
3. {
4. FILE *fptr;
5. int id;
6. char name[30];
7. float salary;
8. fptr = fopen("emp.txt", "w+");/* open for writing */
9. if (fptr == NULL)
10. {
11. printf("File does not exists \n");
12. return;
13. }
14. printf("Enter the id\n");
15. scanf("%d", &id);
16. fprintf(fptr, "Id= %d\n", id);
17. printf("Enter the name \n");
18. scanf("%s", name);
19. fprintf(fptr, "Name= %s\n", name);
20. printf("Enter the salary\n");
21. scanf("%f", &salary);
22. fprintf(fptr, "Salary= %.2f\n", salary);
23. fclose(fptr);
24. }

Output:

Enter the id
1
Enter the name
sonoo
Enter the salary
120000

Now open file from current directory. For windows operating system, go to TC\bin directory, you
will see emp.txt file. It will have following information.

emp.txt

Id= 1
Name= sonoo
Salary= 120000
C fputc() and fgetc()

Writing File : fputc() function

The fputc() function is used to write a single character into file. It outputs a character to a stream.

Syntax:

1. int fputc(int c, FILE *stream)


1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. fp = fopen("file1.txt", "w");//opening file
5. fputc('a',fp);//writing single character into file
6. fclose(fp);//closing file
7. }

file1.txt

Reading File : fgetc() function

The fgetc() function returns a single character from the file. It gets a character from the stream. It
returns EOF at the end of file.

Syntax:

1. int fgetc(FILE *stream)

Example:

1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char c;
6. clrscr();
7. fp=fopen("myfile.txt","r");
8.
9. while((c=fgetc(fp))!=EOF){
10. printf("%c",c);
11. }
12. fclose(fp);
13. getch();
14. }

myfile.txt

this is simple text message


C fputs() and fgets()

The fputs() and fgets() in C programming are used to write and read string from stream. Let's see
examples of writing and reading file using fgets() and fgets() functions.

Writing File : fputs() function

The fputs() function writes a line of characters into file. It outputs string to a stream.

1. int fputs(const char *s, FILE *stream)

Example:

1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. clrscr();
6.
7. fp=fopen("myfile2.txt","w");
8. fputs("hello c programming",fp);
9.
10. fclose(fp);
11. getch();
12. }

myfile2.txt
hello c programming

Reading File : fgets() function

The fgets() function reads a line of characters from file. It gets string from a stream.

Syntax:

1. char* fgets(char *s, int n, FILE *stream)

Example:

1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char text[300];
6. clrscr();
7.
8. fp=fopen("myfile2.txt","r");
9. printf("%s",fgets(text,200,fp));
10.
11. fclose(fp);
12. getch();
13. }

Output:

hello c programming
C fseek() function

The fseek() function is used to set the file pointer to the specified offset. It is used to write data
into file at desired location.

Syntax:

1. int fseek(FILE *stream, long int offset, int whence)

There are 3 constants used in the fseek() function for whence: SEEK_SET, SEEK_CUR and
SEEK_END.
Example:

1. #include <stdio.h>
2. void main(){
3. FILE *fp;
4.
5. fp = fopen("myfile.txt","w+");
6. fputs("This is javatpoint", fp);
7.
8. fseek( fp, 7, SEEK_SET );
9. fputs("sonoo jaiswal", fp);
10. fclose(fp);
11. }

myfile.txt

This is sonoo jaiswal


C rewind() function

The rewind() function sets the file pointer at the beginning of the stream. It is useful if you have to
use stream many times.

Syntax:

1. void rewind(FILE *stream)

File: file.txt

1. this is a simple text

File: rewind.c

1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char c;
6. clrscr();
7. fp=fopen("file.txt","r");
8.
9. while((c=fgetc(fp))!=EOF){
10. printf("%c",c);
11. }
12.
13. rewind(fp);//moves the file pointer at beginning of the file
14.
15. while((c=fgetc(fp))!=EOF){
16. printf("%c",c);
17. }
18.
19. fclose(fp);
20. getch();
21. }

Output:

this is a simple textthis is a simple text

As you can see, rewind() function moves the file pointer at beginning of the file that is why "this is
simple text" is printed 2 times. If you don't call rewind() function, "this is simple text" will be
printed only once.

C ftell()at function

The ftell() function returns the current file position of the specified stream. We can use ftell()
function to get the total size of a file after moving file pointer at the end of file. We can use
SEEK_END constant to move the file pointer at the end of file.

Syntax:

1. long int ftell(FILE *stream)

Example:

File: ftell.c

1. #include <stdio.h>
2. #include <conio.h>
3. void main (){
4. FILE *fp;
5. int length;
6. clrscr();
7. fp = fopen("file.txt", "r");
8. fseek(fp, 0, SEEK_END);
9.
10. length = ftell(fp);
11.
12. fclose(fp);
13. printf("Size of file: %d bytes", length);
14. getch();
15. }

Output:

Size of file: 21 bytes


Small Applications of database management system:-

Nowadays, any business that has small or large amounts of data needs a database to store and
manage the information. The database is an easy, reliable, secure, and efficient way to maintain
business information. There are many applications where databases are used.

In this article, we will discuss some of the applications of databases, which are mentioned below:

1. Universities:

It is an undeniable application of the database. Universities have so much data which can be stored
in the database, such as student information, teacher information, non-teaching staff information,
course information, section information, grade report information, and many more. University
information is kept safe and secure in the database.

Anyone who needs information about the student, teacher, or course can easily retrieve it from the
database. Everything needs to be maintained because even after ten years, information may be
required, and the information may be useful, so maintaining complete information is the primary
responsibility of any university or educational institution.

2. Banking:

It is one of the major applications of databases. Banks have a huge amount of data as millions of
people have accounts that need to be maintained properly. The database keeps the record of each
user in a systematic manner. Banking databases store a lot of information about account holders. It
stores customer details, asset details, banking transactions, balance sheets, credit card and debit
card details, loans, fixed deposits, and much more. Everything is maintained with the help of a
database.

3. Railway Reservation System:

It is an inevitable area of application of databases. They store information such as passenger name,
mobile number, booking status, reservation details, train schedule, employee information, account
details, seating arrangement, route & alternate route details, etc. All the information needs to be
maintained, so railways use a database management system for their efficient storage and retrieval
purpose.

4. Social Media Sites:

Nowadays, everyone has a smartphone and accounts on various social media sites like Facebook,
LinkedIn, Pinterest, Twitter, Instagram, etc. People can chat with their friends and family and
make new friends from all over the world. Social media has millions of accounts, which means they
have a huge amount of data that needs to be stored and maintained. Social media sites use
databases to store information about users, images, videos, chats, etc.

5. Library Management System:

There are hundreds and thousands of books in the library, so it is not easy to maintain the records
of the books in a register or diary, so a database management system is used which maintains the
information of the library efficiently. The library database stores information like book name, issue
date, author name, book availability, book issuer name, book return details, etc.

6. E-commerce Websites:

E-commerce websites are one of the prominent applications of the database. Websites such as
Flipkart, Myntra, Amazon, Nykaa, Snapdeal, Shopify, and many more, are online shopping websites
where people buy items online. These websites have so much data. These websites use databases
to securely store and maintain customer details, product details, dealer details, purchase details,
bank & card details, transactions details, invoice details, etc. You can analyze the sales and
maintain the inventory with the help of a database.

7. Medical:

There is a lot of important data collection in the medical field, so it is necessary to use the
database to store data related to the medical field, such as patient details, medicine details,
practitioner details, surgeon details, appointment details, doctor schedule, patient discharge
details, payment detail, invoices, and other medical records. The database management system is a
boon for the medical field because it helps doctors to monitor their patients and provide better
care.

8. Accounting and Finance:

When there is big data regarding accounting and finance, there is a need to maintain a large
amount of data, which is done with the help of a database. The database stores data such as
accounting details, bank details, purchases of stocks, invoice details, sales records, asset details,
etc. Accounting and finance database helps in maintaining and analyzing historical data.

9. Industries:

The database management system is the main priority of industries because they need to store
huge amounts of data. The industry database stores customer details, sales records, product lists,
transactions, etc. All the information is kept secure and maintained by the database.

10. Airline Reservation System:

It is one of the applications of database management systems that contain data such as passenger
name, passenger check-in, passenger departure, flight schedule, number of flights, distance from
source to destination, reservation information, pilot details, accounting detail, route detail, etc.
The database provides maintenance and security to airline data.

11. Telecommunication:

We cannot deny that telecommunication has brought a remarkable revolution worldwide. The
Telecom field has huge data, and it is very difficult to manage big data without a database; that is
why a telecom database is required, which stores data such as customer names, phone numbers,
calling details, prepaid & post-paid connection records, network usage, bill details, balance details,
etc.

12. Manufacturing:

In the manufacturing field, a lot of data needs to be maintained regarding supply chain
management, so the database maintains the data such as product details, customer information,
order details, purchase details, payment info, worker's details, invoice, etc. Manufacturing
companies produce and supply products every day, so it is important to use a database.
13. Human Resource Management:

Any organization will definitely have employees, and if there are a large number of employees,
then it becomes essential to store data in a database as it maintains and securely saves the data,
which can be retrieved and accessed when required. The human resource database stores data
such as employee name, joining details, designation, salary details, tax information, benefits &
goodies details, etc.

14. Broadcasting:

Broadcasting is distributing video and audio content to a dispersed audience by television, radio,
or other means. Broadcasting database stores data such as subscriber information, event
recordings, event schedules, etc., so it becomes important to store broadcasting data in the
database.

15. Insurance:

An insurance company needs a database to store large amounts of data. Insurance database stores
data such as policy details, user details, buyer details, payment details, nominee details, address
details, etc.

Next →← Prev

C Preprocessor Directives

The C preprocessor is a micro processor that is used by compiler to transform your


code before compilation. It is called micro preprocessor because it allows us to add
macros.
Note: Proprocessor direcives are executed before compilation.

All preprocessor directives starts with hash # symbol.

o #include
o #define
o #undef
o #ifdef
o #ifndef
o #if
o #else
o #elif
o #endif
o #error
o #pragma

C Macros

A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define
directive. There are two types of macros:

1. Object-like Macros
2. Function-like Macros

Object-like Macros

The object-like macro is an identifier that is replaced by value. It is widely used to represent
numeric constants. For example:

1. #define PI 3.14

Here, PI is the macro name which will be replaced by the value 3.14.

Function-like Macros

The function-like macro looks like function call. For example:

1. #define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name.

Visit #define to see the full example of object-like and function-like macros.

C Predefined Macros

ANSI C defines many predefined macros that can be used in c program.

M Description
o. acro

_ represents current date in "MMM DD YYYY" format.


DATE_

_ represents current time in "HH:MM:SS" format.


TIME_

_ represents current file name.


FILE_

_ represents current line number.


LINE_
_ It is defined as 1 when compiler complies with the
STDC_ ANSI standard.

C predefined macros example

File: simple.c

1. #include<stdio.h>
2. int main(){
3. printf("File :%s\n", __FILE__ );
4. printf("Date :%s\n", __DATE__ );
5. printf("Time :%s\n", __TIME__ );
6. printf("Line :%d\n", __LINE__ );
7. printf("STDC :%d\n", __STDC__ );
8. return 0;
9. }

Output:

File :simple.c
Date :Dec 6 2015
Time :12:28:46
Line :6
STDC :1
C #include

The #include preprocessor directive is used to paste code of given file into current file. It is used
include system-defined and user-defined header files. If included file is not found, compiler
renders error.

By the use of #include directive, we provide information to the preprocessor where to look for the
header files. There are two variants to use #include directive.

1. #include <filename>
2. #include "filename"

The #include <filename> tells the compiler to look for the directory where system header files are
held. In UNIX, it is \usr\include directory.

The #include "filename" tells the compiler to look in the current directory from where program is
running.
#include directive example

Let's see a simple example of #include directive. In this program, we are including stdio.h file
because printf() function is defined in this file.

1. #include<stdio.h>
2. int main(){
3. printf("Hello C");
4. return 0;
5. }

Output:

Hello C

#include notes:

Note 1: In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is
treated as filename.

Note 2: In #include directive, backslash is considered as normal text not escape sequence. So in
case of #include <a\nb>, a\nb is treated as filename.

Note 3: You can use only comment after filename otherwise it will give error.

C #define

The #define preprocessor directive is used to define constant or micro substitution. It can use any
basic data type.

Syntax:

1. #define token value

Let's see an example of #define to define a constant.

1. #include <stdio.h>
2. #define PI 3.14
3. main() {
4. printf("%f",PI);
5. }

Output:

3.140000
1. #include <stdio.h>
2. #define MIN(a,b) ((a)<(b)?(a):(b))
3. void main() {
4. printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));
5. }

Output:

Minimum between 10 and 20 is: 10


C #undef

The #undef preprocessor directive is used to undefine the constant or macro defined by #define.

Syntax:

1. #undef token

Let's see a simple example to define and undefine a constant.

5.3M
458
Hello Java Program for Beginners

1. #include <stdio.h>
2. #define PI 3.14
3. #undef PI
4. main() {
5. printf("%f",PI);
6. }

Output:

Compile Time Error: 'PI' undeclared

The #undef directive is used to define the preprocessor constant to a limited scope so that you
can declare constant again.

Let's see an example where we are defining and undefining number variable. But before being
undefined, it was used by square variable.

1. #include <stdio.h>
2. #define number 15
3. int square=number*number;
4. #undef number
5. main() {
6. printf("%d",square);
7. }

Output:

225
C #ifdef

The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the
code otherwise #else code is executed, if present.

Syntax:

1. #ifdef MACRO
2. //code
3. #endif

Syntax with #else:

1. #ifdef MACRO
2. //successful code
3. #else
4. //else code
5. #endif

C #ifdef example

Let's see a simple example to use #ifdef preprocessor directive.

1. #include <stdio.h>
2. #include <conio.h>
3. #define NOINPUT
4. void main() {
5. int a=0;
6. #ifdef NOINPUT
7. a=2;
8. #else
9. printf("Enter a:");
10. scanf("%d", &a);
11. #endif
12. printf("Value of a: %d\n", a);
13. getch();
14. }

Output:
Value of a: 2

But, if you don't define NOINPUT, it will ask user to enter a number.

1. #include <stdio.h>
2. #include <conio.h>
3. void main() {
4. int a=0;
5. #ifdef NOINPUT
6. a=2;
7. #else
8. printf("Enter a:");
9. scanf("%d", &a);
10. #endif
11.
12. printf("Value of a: %d\n", a);
13. getch();
14. }
15. Enter a:5
16. Value of a: 5
1. #ifndef MACRO
2. //successful code
3. #else
4. //else code
5. #endif

C #ifndef example

Let's see a simple example to use #ifndef preprocessor directive.

1. #include <stdio.h>
2. #include <conio.h>
3. #define INPUT
4. void main() {
5. int a=0;
6. #ifndef INPUT
7. a=2;
8. #else
9. printf("Enter a:");
10. scanf("%d", &a);
11. #endif
12. printf("Value of a: %d\n", a);
13. getch();
14. }
Output:

Enter a:5
Value of a: 5

But, if you don't define INPUT, it will execute the code of #ifndef.

1. #include <stdio.h>
2. #include <conio.h>
3. void main() {
4. int a=0;
5. #ifndef INPUT
6. a=2;
7. #else
8. printf("Enter a:");
9. scanf("%d", &a);
10. #endif
11. printf("Value of a: %d\n", a);
12. getch();
13. }

Output:

Value of a: 2
C #if

The #if preprocessor directive evaluates the expression or condition. If condition is true, it
executes the code otherwise #elseif or #else or #endif code is executed.

Syntax:

1. #if expression
2. //code
3. #endif

Syntax with #else:

1. #if expression
2. //code
3. #endif

Syntax with #else:

1. #if expression
2. //if code
3. #else
4. //else code
5. #endif

Syntax with #elif and #else:

1. #if expression
2. //if code
3. #elif expression
4. //elif code
5. #else
6. //else code
7. #endif

C #if example

Let's see a simple example to use #if preprocessor directive.

1. #include <stdio.h>
2. #include <conio.h>
3. #define NUMBER 0
4. void main() {
5. #if (NUMBER==0)
6. printf("Value of Number is: %d",NUMBER);
7. #endif
8. getch();
9. }

Output:

Value of Number is: 0


1. #include <stdio.h>
2. #include <conio.h>
3. #define NUMBER 1
4. void main() {
5. clrscr();
6. #if (NUMBER==0)
7. printf("1 Value of Number is: %d",NUMBER);
8. #endif
9.
10. #if (NUMBER==1)
11. printf("2 Value of Number is: %d",NUMBER);
12. #endif
13. getch();
14. }
Output:

2 Value of Number is: 1


C #else

The #else preprocessor directive evaluates the expression or condition if condition of #if is false.
It can be used with #if, #elif, #ifdef and #ifndef directives.

Syntax:

1. #if expression
2. //if code
3. #else
4. //else code
5. #endif

Syntax with #elif:

1. #if expression
2. //if code
3. #elif expression
4. //elif code
5. #else
6. //else code
7. #endif

C #else example

Let's see a simple example to use #else preprocessor directive.

1. #include <stdio.h>
2. #include <conio.h>
3. #define NUMBER 1
4. void main() {
5. #if NUMBER==0
6. printf("Value of Number is: %d",NUMBER);
7. #else
8. print("Value of Number is non-zero");
9. #endif
10. getch();
11. }
C #error
The #error preprocessor directive indicates error. The compiler gives fatal error if
#error directive is found and skips further compilation process.

C #error example

Let's see a simple example to use #error preprocessor directive.

#include<stdio.h>
#ifndef __MATH_H
#error First include then compile
#else
void main(){
float a;
a=sqrt(7);
printf("%f",a);
}
#endif

Output:

C++ vs Java

Compile Time Error: First include then compile

But, if you include math.h, it does not gives error.

#include<stdio.h>
#include<math.h>
#ifndef __MATH_H
#error First include then compile
#else
void main(){
float a;
a=sqrt(7);
printf("%f",a);
}
#endif

Output:

2.645751

Next →← Prev
C #pragma

The #pragma preprocessor directive is used to provide additional information to the compiler.
The #pragma directive is used by the compiler to offer machine or operating-system feature.

Syntax:

1. #pragma token

Different compilers can provide different usage of #pragma directive.

6.4M
721
Difference between JDK, JRE, and JVM
Next
Stay

The turbo C++ compiler supports following #pragma directives.

1. #pragma argsused
2. #pragma exit
3. #pragma hdrfile
4. #pragma hdrstop
5. #pragma inline
6. #pragma option
7. #pragma saveregs
8. #pragma startup
9. #pragma warn

Let's see a simple example to use #pragma preprocessor directive.

1. #include<stdio.h>
2. #include<conio.h>
3.
4. void func() ;
5.
6. #pragma startup func
7. #pragma exit func
8.
9. void main(){
10. printf("\nI am in main");
11. getch();
12. }
13.
14. void func(){
15. printf("\nI am in func");
16. getch();
17. }

Output:

I am in func

You might also like