SlideShare a Scribd company logo
FILE HANDLING IN C
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.
1. Creation of the new file
2. Opening an existing file
3. Reading from the file
4. Writing to the file
5. Deleting the file
Functions for file handling:
No. Function Description
1 fopen() opens new or existing file
2 fprintf() write data into the file
3 fscanf() reads data from the file
4 fputc() writes a character into the file
5 fgetc() reads a character from file
6 fclose() closes the file
7 fseek() sets the file pointer to given position
8 fputw() writes an integer to file
9 fgetw() reads an integer from file
10 ftell() returns current position
11 rewind() sets the file pointer to the beginning of
the file
Opening File: fopen()
We must open a file before it can be read, write, or update. The fopen() function is used to
open a file. The syntax of the fopen() is given below.
1. FILE *fopen( const char * filename, const char * mode );
The fopen() function accepts two parameters:
o The file name (string). If the file is stored at some specific location, then we must
mention the path at which the file is stored. For example, a file name can be
like "c://some_folder/some_file.ext".
o The mode in which the file is to be opened. It is a string.
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
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:
 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, ...])
Example:
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 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)
Example:
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
a
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 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
Random Access To File:
There is no need to read each record sequentially, if
we want to access a particular record.C supports
these functions for random access file processing.
1. fseek()
2. ftell()
3. rewind()
fseek():
Thisfunction isused for seekingthepointer position in thefileat thespecified byte.
Syntax: fseek( filepointer,displacement, pointer position);
Where
file pointer ---- It isthepointer which pointsto thefile.
displacement ---- It ispositiveor negative.Thisisthenumber of byteswhich areskipped backward (if
negative) or forward( if positive) from thecurrent position.Thisisattached with Lbecausethisisalong
integer.
Pointer position:
Thissetsthepointer position in thefile.
Value pointer position
0 Beginning of file.
1 Current position
2 End of file
Example:
1) fseek( p,10L,0)
0 means pointer position is on beginning of the file,from this
statement pointer position is skipped 10 bytes from the
beginning of the file.
2)fseek( p,5L,1)
1 means current position of the pointer position.From this
statement pointer position is skipped 5 bytes forward from
the current position.
3)fseek(p,-5L,1)
From this statement pointer position is skipped 5 bytes
backward from the current position.
ftell():
 This function returns the value of the current pointer
position in the file.The value is count from the
beginning of the file.
Syntax: ftell(fptr);
Where fptr is a file pointer.
rewind():
 This function is used to move the file pointer to the
beginning of the given file.
Syntax: rewind( fptr);
Where fptr is a file pointer.
Binary files:
Binary files are very similar to arrays of structures, except
the structures are in a disk file rather than in an array in
memory. Because the structures in a binary file are on disk,
you can create very large collections of them (limited only
by your available disk space). They are also permanent
and always available. The only disadvantage is the
slowness that comes from disk access time.
Binary files have two features that distinguish them from
text files:
 You can jump instantly to any structure in the file, which
provides random access as in an array.
 You can change the contents of a structure anywhere in
the file at any time.
Binary files also usually have faster read and write times
than text files, because a binary image of the record is
stored directly from memory to disk (or vice versa). In a text
file, everything has to be converted back and forth to text,
and this takes time.
Command Line Arguments in C
 The arguments passed from command line are
called command line arguments. These arguments
are handled by main() function.
 To support command line argument, you need to
change the structure of main() function as given
below.
 int main(int argc, char *argv[] )
 Here, argc counts the number of arguments. It
counts the file name as the first argument.
 The argv[] contains the total number of arguments.
The first argument is the file name always.
Example
Let's see the example of command line arguments where we are passing one argument with
file name.
1. #include <stdio.h>
2. void main(int argc, char *argv[] ) {
3.
4. printf("Program name is: %sn", argv[0]);
5.
6. if(argc < 2){
7. printf("No argument passed through command line.n");
8. }
9. else{
10. printf("First argument is: %sn", argv[1]);
11. }
12. }
1. program.exe hello
Output:
Program name is: program
First argument is: hello
Run the program as follows in Windows from command line:
1. program.exe hello
Output:
Program name is: program
First argument is: hello
If you pass many arguments, it will print only one.
1. ./program hello c how r u
Output:
Program name is: program
First argument is: hello
But if you pass many arguments within double quote, all arguments will be treated as a
single argument only.
1. ./program "hello c how r u"
Output:
Program name is: program
First argument is: hello c how r u
You can write your program to print all the arguments. In this program, we are printing only
argv[1], that is why it is printing only one argument.
Ad

More Related Content

What's hot (20)

Files in c++
Files in c++Files in c++
Files in c++
Selvin Josy Bai Somu
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
Appili Vamsi Krishna
 
Pointers in c language
Pointers in c languagePointers in c language
Pointers in c language
Tanmay Modi
 
File in c
File in cFile in c
File in c
Prabhu Govind
 
Functions in C
Functions in CFunctions in C
Functions in C
Kamal Acharya
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
Shuvongkor Barman
 
Dynamic memory allocation in c
Dynamic memory allocation in cDynamic memory allocation in c
Dynamic memory allocation in c
lavanya marichamy
 
File handling in c
File handling in cFile handling in c
File handling in c
David Livingston J
 
structure and union
structure and unionstructure and union
structure and union
student
 
File in C language
File in C languageFile in C language
File in C language
Manash Kumar Mondal
 
Python file handling
Python file handlingPython file handling
Python file handling
Prof. Dr. K. Adisesha
 
Function in C program
Function in C programFunction in C program
Function in C program
Nurul Zakiah Zamri Tan
 
Pointer in c
Pointer in cPointer in c
Pointer in c
lavanya marichamy
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
v_jk
 
Union in C programming
Union in C programmingUnion in C programming
Union in C programming
Kamal Acharya
 
Function C programming
Function C programmingFunction C programming
Function C programming
Appili Vamsi Krishna
 
Inline function
Inline functionInline function
Inline function
Tech_MX
 
Files and streams
Files and streamsFiles and streams
Files and streams
Pranali Chaudhari
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Viji B
 
C string
C stringC string
C string
University of Potsdam
 

Similar to C Programming Unit-5 (20)

ppt5-190810161800 (1).pdf
ppt5-190810161800 (1).pdfppt5-190810161800 (1).pdf
ppt5-190810161800 (1).pdf
MalligaarjunanN
 
want to learn files,then just use this ppt to learn
want to learn files,then just use this ppt to learnwant to learn files,then just use this ppt to learn
want to learn files,then just use this ppt to learn
nalluribalaji157
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
sangeeta borde
 
pre processor and file handling in c language ppt
pre processor and file handling in c language pptpre processor and file handling in c language ppt
pre processor and file handling in c language ppt
shreyasreddy703
 
Module 5 file cp
Module 5 file cpModule 5 file cp
Module 5 file cp
Amarjith C K
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
sudhakargeruganti
 
Unit5
Unit5Unit5
Unit5
mrecedu
 
Unit 5 dwqb ans
Unit 5 dwqb ansUnit 5 dwqb ans
Unit 5 dwqb ans
Sowri Rajan
 
Handout#01
Handout#01Handout#01
Handout#01
Sunita Milind Dol
 
File management
File managementFile management
File management
lalithambiga kamaraj
 
Programming C- File Handling , File Operation
Programming C- File Handling , File OperationProgramming C- File Handling , File Operation
Programming C- File Handling , File Operation
svkarthik86
 
File Handling in C Programming
File Handling in C ProgrammingFile Handling in C Programming
File Handling in C Programming
RavindraSalunke3
 
Unit 8
Unit 8Unit 8
Unit 8
Keerthi Mutyala
 
Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10
patcha535
 
file handling1
file handling1file handling1
file handling1
student
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
yndaravind
 
File Handling in C
File Handling in CFile Handling in C
File Handling in C
vishnupriyapm4
 
PPS-II UNIT-5 PPT.pptx
PPS-II  UNIT-5 PPT.pptxPPS-II  UNIT-5 PPT.pptx
PPS-II UNIT-5 PPT.pptx
VenkataRangaRaoKommi1
 
File Organization
File OrganizationFile Organization
File Organization
RAMPRAKASH REDDY ARAVA
 
C programming session 08
C programming session 08C programming session 08
C programming session 08
Dushmanta Nath
 
ppt5-190810161800 (1).pdf
ppt5-190810161800 (1).pdfppt5-190810161800 (1).pdf
ppt5-190810161800 (1).pdf
MalligaarjunanN
 
want to learn files,then just use this ppt to learn
want to learn files,then just use this ppt to learnwant to learn files,then just use this ppt to learn
want to learn files,then just use this ppt to learn
nalluribalaji157
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
sangeeta borde
 
pre processor and file handling in c language ppt
pre processor and file handling in c language pptpre processor and file handling in c language ppt
pre processor and file handling in c language ppt
shreyasreddy703
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
sudhakargeruganti
 
Programming C- File Handling , File Operation
Programming C- File Handling , File OperationProgramming C- File Handling , File Operation
Programming C- File Handling , File Operation
svkarthik86
 
File Handling in C Programming
File Handling in C ProgrammingFile Handling in C Programming
File Handling in C Programming
RavindraSalunke3
 
Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10
patcha535
 
file handling1
file handling1file handling1
file handling1
student
 
C programming session 08
C programming session 08C programming session 08
C programming session 08
Dushmanta Nath
 
Ad

More from Vikram Nandini (20)

IoT: From Copper strip to Gold Bar
IoT: From Copper strip to Gold BarIoT: From Copper strip to Gold Bar
IoT: From Copper strip to Gold Bar
Vikram Nandini
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
Vikram Nandini
 
Linux File Trees and Commands
Linux File Trees and CommandsLinux File Trees and Commands
Linux File Trees and Commands
Vikram Nandini
 
Introduction to Linux & Basic Commands
Introduction to Linux & Basic CommandsIntroduction to Linux & Basic Commands
Introduction to Linux & Basic Commands
Vikram Nandini
 
INTRODUCTION to OOAD
INTRODUCTION to OOADINTRODUCTION to OOAD
INTRODUCTION to OOAD
Vikram Nandini
 
Ethics
EthicsEthics
Ethics
Vikram Nandini
 
Manufacturing - II Part
Manufacturing - II PartManufacturing - II Part
Manufacturing - II Part
Vikram Nandini
 
Manufacturing
ManufacturingManufacturing
Manufacturing
Vikram Nandini
 
Business Models
Business ModelsBusiness Models
Business Models
Vikram Nandini
 
Prototyping Online Components
Prototyping Online ComponentsPrototyping Online Components
Prototyping Online Components
Vikram Nandini
 
Artificial Neural Networks
Artificial Neural NetworksArtificial Neural Networks
Artificial Neural Networks
Vikram Nandini
 
IoT-Prototyping
IoT-PrototypingIoT-Prototyping
IoT-Prototyping
Vikram Nandini
 
Design Principles for Connected Devices
Design Principles for Connected DevicesDesign Principles for Connected Devices
Design Principles for Connected Devices
Vikram Nandini
 
Introduction to IoT
Introduction to IoTIntroduction to IoT
Introduction to IoT
Vikram Nandini
 
Embedded decices
Embedded decicesEmbedded decices
Embedded decices
Vikram Nandini
 
Communication in the IoT
Communication in the IoTCommunication in the IoT
Communication in the IoT
Vikram Nandini
 
Introduction to Cyber Security
Introduction to Cyber SecurityIntroduction to Cyber Security
Introduction to Cyber Security
Vikram Nandini
 
cloud computing UNIT-2.pdf
cloud computing UNIT-2.pdfcloud computing UNIT-2.pdf
cloud computing UNIT-2.pdf
Vikram Nandini
 
Introduction to Web Technologies
Introduction to Web TechnologiesIntroduction to Web Technologies
Introduction to Web Technologies
Vikram Nandini
 
Cascading Style Sheets
Cascading Style SheetsCascading Style Sheets
Cascading Style Sheets
Vikram Nandini
 
IoT: From Copper strip to Gold Bar
IoT: From Copper strip to Gold BarIoT: From Copper strip to Gold Bar
IoT: From Copper strip to Gold Bar
Vikram Nandini
 
Linux File Trees and Commands
Linux File Trees and CommandsLinux File Trees and Commands
Linux File Trees and Commands
Vikram Nandini
 
Introduction to Linux & Basic Commands
Introduction to Linux & Basic CommandsIntroduction to Linux & Basic Commands
Introduction to Linux & Basic Commands
Vikram Nandini
 
Manufacturing - II Part
Manufacturing - II PartManufacturing - II Part
Manufacturing - II Part
Vikram Nandini
 
Prototyping Online Components
Prototyping Online ComponentsPrototyping Online Components
Prototyping Online Components
Vikram Nandini
 
Artificial Neural Networks
Artificial Neural NetworksArtificial Neural Networks
Artificial Neural Networks
Vikram Nandini
 
Design Principles for Connected Devices
Design Principles for Connected DevicesDesign Principles for Connected Devices
Design Principles for Connected Devices
Vikram Nandini
 
Communication in the IoT
Communication in the IoTCommunication in the IoT
Communication in the IoT
Vikram Nandini
 
Introduction to Cyber Security
Introduction to Cyber SecurityIntroduction to Cyber Security
Introduction to Cyber Security
Vikram Nandini
 
cloud computing UNIT-2.pdf
cloud computing UNIT-2.pdfcloud computing UNIT-2.pdf
cloud computing UNIT-2.pdf
Vikram Nandini
 
Introduction to Web Technologies
Introduction to Web TechnologiesIntroduction to Web Technologies
Introduction to Web Technologies
Vikram Nandini
 
Cascading Style Sheets
Cascading Style SheetsCascading Style Sheets
Cascading Style Sheets
Vikram Nandini
 
Ad

Recently uploaded (20)

Ancient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian HistoryAncient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian History
Virag Sontakke
 
Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
antiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidenceantiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidence
PrachiSontakke5
 
UPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guideUPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guide
abmerca
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptxANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
Mayuri Chavan
 
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
Dr. Nasir Mustafa
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)
Mohamed Rizk Khodair
 
How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18
Celine George
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
All About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdfAll About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdf
TechSoup
 
How to Configure Scheduled Actions in odoo 18
How to Configure Scheduled Actions in odoo 18How to Configure Scheduled Actions in odoo 18
How to Configure Scheduled Actions in odoo 18
Celine George
 
Drugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdfDrugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdf
crewot855
 
Ancient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian HistoryAncient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian History
Virag Sontakke
 
Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
antiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidenceantiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidence
PrachiSontakke5
 
UPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guideUPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guide
abmerca
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptxANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
Mayuri Chavan
 
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
Dr. Nasir Mustafa
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)
Mohamed Rizk Khodair
 
How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18
Celine George
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
All About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdfAll About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdf
TechSoup
 
How to Configure Scheduled Actions in odoo 18
How to Configure Scheduled Actions in odoo 18How to Configure Scheduled Actions in odoo 18
How to Configure Scheduled Actions in odoo 18
Celine George
 
Drugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdfDrugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdf
crewot855
 

C Programming Unit-5

  • 2. 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. 1. Creation of the new file 2. Opening an existing file 3. Reading from the file 4. Writing to the file 5. Deleting the file
  • 3. Functions for file handling: No. Function Description 1 fopen() opens new or existing file 2 fprintf() write data into the file 3 fscanf() reads data from the file 4 fputc() writes a character into the file 5 fgetc() reads a character from file 6 fclose() closes the file 7 fseek() sets the file pointer to given position 8 fputw() writes an integer to file 9 fgetw() reads an integer from file 10 ftell() returns current position 11 rewind() sets the file pointer to the beginning of the file
  • 4. Opening File: fopen() We must open a file before it can be read, write, or update. The fopen() function is used to open a file. The syntax of the fopen() is given below. 1. FILE *fopen( const char * filename, const char * mode ); The fopen() function accepts two parameters: o The file name (string). If the file is stored at some specific location, then we must mention the path at which the file is stored. For example, a file name can be like "c://some_folder/some_file.ext". o The mode in which the file is to be opened. It is a string.
  • 5. 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
  • 6. 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 ); }
  • 7. Closing File: fclose()  The fclose() function is used to close a file. The file must be closed after performing all the operations on it. The syntax of fclose() function is given below:  int fclose( FILE *fp );
  • 8. 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, ...]) Example: 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. }
  • 9. 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...
  • 10. 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) Example: 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 a
  • 11. 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
  • 12. 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
  • 13. Random Access To File: There is no need to read each record sequentially, if we want to access a particular record.C supports these functions for random access file processing. 1. fseek() 2. ftell() 3. rewind()
  • 14. fseek(): Thisfunction isused for seekingthepointer position in thefileat thespecified byte. Syntax: fseek( filepointer,displacement, pointer position); Where file pointer ---- It isthepointer which pointsto thefile. displacement ---- It ispositiveor negative.Thisisthenumber of byteswhich areskipped backward (if negative) or forward( if positive) from thecurrent position.Thisisattached with Lbecausethisisalong integer. Pointer position: Thissetsthepointer position in thefile. Value pointer position 0 Beginning of file. 1 Current position 2 End of file
  • 15. Example: 1) fseek( p,10L,0) 0 means pointer position is on beginning of the file,from this statement pointer position is skipped 10 bytes from the beginning of the file. 2)fseek( p,5L,1) 1 means current position of the pointer position.From this statement pointer position is skipped 5 bytes forward from the current position. 3)fseek(p,-5L,1) From this statement pointer position is skipped 5 bytes backward from the current position.
  • 16. ftell():  This function returns the value of the current pointer position in the file.The value is count from the beginning of the file. Syntax: ftell(fptr); Where fptr is a file pointer. rewind():  This function is used to move the file pointer to the beginning of the given file. Syntax: rewind( fptr); Where fptr is a file pointer.
  • 17. Binary files: Binary files are very similar to arrays of structures, except the structures are in a disk file rather than in an array in memory. Because the structures in a binary file are on disk, you can create very large collections of them (limited only by your available disk space). They are also permanent and always available. The only disadvantage is the slowness that comes from disk access time. Binary files have two features that distinguish them from text files:  You can jump instantly to any structure in the file, which provides random access as in an array.  You can change the contents of a structure anywhere in the file at any time. Binary files also usually have faster read and write times than text files, because a binary image of the record is stored directly from memory to disk (or vice versa). In a text file, everything has to be converted back and forth to text, and this takes time.
  • 18. Command Line Arguments in C  The arguments passed from command line are called command line arguments. These arguments are handled by main() function.  To support command line argument, you need to change the structure of main() function as given below.  int main(int argc, char *argv[] )  Here, argc counts the number of arguments. It counts the file name as the first argument.  The argv[] contains the total number of arguments. The first argument is the file name always.
  • 19. Example Let's see the example of command line arguments where we are passing one argument with file name. 1. #include <stdio.h> 2. void main(int argc, char *argv[] ) { 3. 4. printf("Program name is: %sn", argv[0]); 5. 6. if(argc < 2){ 7. printf("No argument passed through command line.n"); 8. } 9. else{ 10. printf("First argument is: %sn", argv[1]); 11. } 12. } 1. program.exe hello Output: Program name is: program First argument is: hello
  • 20. Run the program as follows in Windows from command line: 1. program.exe hello Output: Program name is: program First argument is: hello If you pass many arguments, it will print only one. 1. ./program hello c how r u Output: Program name is: program First argument is: hello But if you pass many arguments within double quote, all arguments will be treated as a single argument only. 1. ./program "hello c how r u" Output: Program name is: program First argument is: hello c how r u You can write your program to print all the arguments. In this program, we are printing only argv[1], that is why it is printing only one argument.
  翻译: