Unit 4 Adv C
Unit 4 Adv C
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.
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.
File Operations
In C, you can perform four major operations on files, either text or binary:
3. Closing a file
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 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
M During
Meaning of Mode
ode Inexistence of file
M During
Meaning of Mode
ode Inexistence of file
Closing a File
The file (both text and binary) should be closed after reading/writing
fclose(fptr);
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.
#include<stdio.h>
#include<stdlib.h>
intmain()
{
int num;
FILE *fptr;
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
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.
#include<stdio.h>
#include<stdlib.h>
intmain()
{
int num;
FILE *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.
Functions fread() and fwrite() are used for reading from and writing to a file on the disk
respectively in case of binary files.
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
#include<stdio.h>
#include<stdlib.h>
structthreeNum
{
int n1, n2, n3;
};
intmain()
{
int n;
structthreeNumnum;
FILE *fptr;
return0;
}
Function fread() also take 4 arguments similar to the fwrite() function as above.
fread(addressData, sizeData, numbersData, pointerToFile);
#include<stdio.h>
#include<stdlib.h>
structthreeNum
{
int n1, n2, n3;
};
intmain()
{
int n;
structthreeNumnum;
FILE *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()
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.
When
Meaning
ce
SEEK
Starts the offset from the end of the file.
_END
#include<stdio.h>
#include<stdlib.h>
structthreeNum
{
int n1, n2, n3;
};
intmain()
{
int n;
structthreeNumnum;
FILE *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
They can hold a higher amount of data, are not readable easily, and provides better security than
text files.
Mode Description
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
#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:
The fprintf() function is used to write set of characters into file. It sends formatted output to a
stream.
Syntax:
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:
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:
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()
The fputc() function is used to write a single character into file. It outputs a character to a stream.
Syntax:
file1.txt
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:
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
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.
The fputs() function writes a line of characters into file. It outputs string to a 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
The fgets() function reads a line of characters from file. It gets string from a stream.
Syntax:
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:
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
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:
File: file.txt
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:
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:
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:
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.
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.
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.
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.
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.
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
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
Visit #define to see the full example of object-like and function-like macros.
C Predefined Macros
M Description
o. acro
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. #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:
The #undef preprocessor directive is used to undefine the constant or macro defined by #define.
Syntax:
1. #undef token
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:
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
1. #ifdef MACRO
2. //successful code
3. #else
4. //else code
5. #endif
C #ifdef example
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
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
1. #if expression
2. //code
3. #endif
1. #if expression
2. //if code
3. #else
4. //else code
5. #endif
1. #if expression
2. //if code
3. #elif expression
4. //elif code
5. #else
6. //else code
7. #endif
C #if example
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:
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
1. #if expression
2. //if code
3. #elif expression
4. //elif code
5. #else
6. //else code
7. #endif
C #else example
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
#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
#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
6.4M
721
Difference between JDK, JRE, and JVM
Next
Stay
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
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