SlideShare a Scribd company logo
1 of 34
Developed by www.futureforyou.net & www.eshikshak.co.in
 A collection of data or information that are
stored on a computer known as file
 A file is a collection of bytes stored on a
secondary storage device.
 There are four different types of file
 Data files
 Text files
 Program files
 Directory files
 Different types of file store different types of
information
 A file has a beginning and an end.
 We need a marker to mark the current
position of the file from the beginning (in
terms of bytes) while reading and write
operation, takes place on a file.
 Initially the marker is at the beginning of the
file. We can move the marker to any other
position in the file.
 The new current position can be specified as
an offset from the beginning the file.
 A stream refers to the flow of data (in bytes)
from one place to another (from program to file
or vice-versa).
 There are two types of streams
 Text Stream
▪ It consists of sequence of characters
▪ Each line of characters in the stream may be terminated by a
newline character.
▪ Text streams are used for textual data, which has a
consistent appearance from one environment to another or
from one machine to another
 Binary Stream
▪ It is a series of bytes.
▪ Binary streams are primarily used for non-textual data,
which is required to keep exact contents of the file.
 A text file can be a stream of characters that
a computer can process sequentially.
 It is processed only in forward direction.
 It is opened for one kind of operation
(reading, writing, or appending) at any give
time.
 We can read only one character at a time
from a text file.
 A binary file is a file consisting of collection of
bytes.
 A binary file is also referred to as a character
stream
 A file is identified by its name.
 This name is divided into two parts
 File Name
▪ It consists of alphabets and digits.
▪ Special characters are also supported, but it depends on
the operating system we use.
 Extension
▪ It describes the file type
 Before opening a file, we need to declare a
file pointer. A file pointer is a pointer
variable of type FILE, which is defined in the
“stdio.h” header file.
 A file pointer has the complete information
about file being opened and processed such
as:
 Name of file, mode it is opened in, starting buffer address,
a character pointer that points to the character being read.
 To perform any operation (read or write) on a
file, the file must be brought into memory
from the storage device (hard disk).
 This process of bringing the copy of the file
from disk (secondary storage) to memory
(main storage) is called opening the file.
Mode Meaning
r  Open a text file for reading only. If the file doesn’t exist, it returns null.
w  Opens a file for writing only.
 If file exists, than all the contents of that file are destroyed and new fresh blank file
is copied on the disk and memory with same name
 If file dosen’t exists, a new blank file is created and opened for writing.
 Returns NULL if it is unable to open the file
a  Appends to the existing text file
 Adds data at the end of the file.
 If file doesn’t exists then a new file is created.
 Returns NULL if it is unable to open the file.
rb  Open a binary file for reading
wb  Open a binary file for reading
ab  Append to a binary file
r+  Open a text file for read/write
w+  Opens the existing text file or Creates a text file for read/write
Mode Meaning
a+  Append or create a text file for read/write
r+b  Open a binary file for read/write
w+b  Create a binary file for read/write
a+b  Append a binary file for read/write
 fopen() function, like all the other file-system
functions, uses the head file stdio.h
 The name of the file to be opened is pointed
to by fname
 The string given as the second parameter -
for mode, determines how the file should be
accessed (r-read, w-write a-append).
FILE *fp;
if(fp = fopen(“myfile”,”r”)) == NULL)
{
printf(“Error opening a file”);
exit(1);
}
 To read contents from an existing file, we
need to open that file in read mode that
means “r” mode
 Algorithm to read data from a file:
1. Open the file in read mode
2. Read data from the file
3. Write the data into an output device
4. Repeat steps 3 and 4 untill the end of file
occurs
5. Stop procedure
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
fp=fopen(“clear.c”,”r”);
if(fp==NULL)
print(“Unable to open clear.c”);
else
{
do
{
ch = getc(fp);
putchar(ch);
}while(ch!=EOF);
fclose(fp);
}
}
 Generally, a file contains a large amount of
data.
 In a large file, it is difficult to detect the end
of file while reading.
 In order to mark the end of a text file, a
special character EOF is stored at the end.
 To close a file and dis-associate it with a
stream (file pointer), use fclose() function.
 fclose() returns 0 if the file is closed
successfully
 The fcloseall() closes all the files opened
previously.
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
fp=fopen(“clear.c”,”r”);
if(fp==NULL)
print(“Unable to open clear.c”);
else
{
do
{
ch = getc(fp);// gets the character from file
putchar(ch);
}while(ch!=EOF);
fclose(fp);
}
}
 We can add contents to an existing file
whenever required.
 Perform the following steps to append an
existing file:
1. Declare a file pointer
2. Open the file in append mode
3. Read data from the keyboard
4. Write it into the file
5. Repeat steps 3 and 4 according to until
the user gives input
6. Stop the process
 char *fgets(char *str, int n, FILE *fptr);
 This function reads a character from the file
stream pointed by fptr and stores it in the
character array ‘str’ until a new line character (n)
is read or end of file (EOF) is reached or n-1
characters have been read.
 fputs(const char *str, FILE *fptr);
 This function writes data to the stream pointed to
by fptr, the content of the string stored in ‘str’
#include<stdio.h>
void main()
{
FILE *fp;
char line[280];int ch, i=0;
fp=fopen(“a.dat”,”a”);
if(fp==NULL)
print(“Unable to open clear.c”);
else{
do{
do{
line[i++] = getchar();
}while(line[i-1]!=‘*’);
fputs(line, fp);//Writes string to the file
i=0;
printf(“nPress 1 to continue”);
scanf(“%d”,&ch);
}while(ch==1);
fclose(fp);
printf(“File is successfully created”);
}
 A file can be accessed in two ways:
 Serial access
 Random access
 Generally all the text files are considered to
be sequential files because lines of text (also
called records) are stored in a file
 The beginning of each record in a sequential
file is unpredictable
 Whereas, in random access files, all the
records are in same length.
 To modify the content of a file, open the file with read and
write mode (“r+” or “w+” or “a+”)
 Generally “r+” mode is used for both reading and writing
operation. The procedure is as follows:
1. Initialize a pointer variable
2. Open the file in read and write mode
3. Read data from file and Print it
4. Move the file pointer to the place where we have
the data to be modified and re-write the new data
in that place.
5. Repeat steps 3 and 4 till the end of file reaches.
6. Stop the Process
#include<stdio.h>
struct stock
{
int itid, qty;
char n[100];
float rate;
}it;
void main()
{
FILE *fp; int ch; int r = 0;
fp = fopen(“item.c”, “r+”);
if(fp==NULL)
{
printf(“Unable to open item.c”);
}
}
else{
do{
fread(&it, sizeof(it),1,fp);
printf(“n%d %s %d %f”, it.itid, it.n, it.qty, it.rate);
printf(“n Press 1 to change it?”);
scanf(“%d”,&ch);
if(ch==1)
{
printf(“n Enter Itemid ItemName Quantity & Price”);
scanf(“%d%s%d%f”, &it.itid, it.n, &it.qty, &it.rate);
fseek(fp, r*sizeof(it), 0);
fwrite(&it, sizeof(it),1,fp);
}r++;
}while(!feof(fp));
fclose(fp);
}
}
fseek(FILE *fptr, long offset, int reference)
 Moves the pointer from one record to
another.
 The first argument is the file pointer
 The second argument tells the compiler how
many bytes (offset) the pointer should be
moved from a particular position.
 The third argument is the reference from
where the pointer should be moved n bytes
(specified in the offset).
fseek(FILE *fptr, long offset, int reference)
 The third argument is the reference from
where the pointer should be moved n bytes
as specified in the offset.
 SEEK_END moves the pointer from the end
marker
 SEEK_CUR moves the pointer from the current
position
 SEEK_SET moves the pointer from the beginning
of the file
fseek(FILE *fptr, long offset, int reference)
 Example
 fseek(fptr, size, SEEK_CUR) sets the cursor ahead
from current position by size bytes
 fseek(fptr, -size, SEEK_CUR) sets the cursor back
from current position by size bytes
 fseek(fptr, 0, SEEK_END) sets cursor to the end of
the file
 fseek(fptr, 0, SEEK_SET) sets cursor to the
beginning of the file
File handling in c
File handling in c

More Related Content

What's hot (20)

File handling in C
File handling in CFile handling in C
File handling in C
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
 
File in c
File in cFile in c
File in c
 
Strings
StringsStrings
Strings
 
Strings in python
Strings in pythonStrings in python
Strings in python
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Structure in C
Structure in CStructure in C
Structure in C
 
Union in c language
Union  in c languageUnion  in c language
Union in c language
 
Files and streams
Files and streamsFiles and streams
Files and streams
 
C++ Overview PPT
C++ Overview PPTC++ Overview PPT
C++ Overview PPT
 
Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in c
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programming
 
class and objects
class and objectsclass and objects
class and objects
 
Storage class in C Language
Storage class in C LanguageStorage class in C Language
Storage class in C Language
 
Data types in C
Data types in CData types in C
Data types in C
 
String functions in C
String functions in CString functions in C
String functions in C
 
Linked list
Linked listLinked list
Linked list
 
Control statements in c
Control statements in cControl statements in c
Control statements in c
 

Similar to File handling in c

Mesics lecture files in 'c'
Mesics lecture   files in 'c'Mesics lecture   files in 'c'
Mesics lecture files in 'c'eShikshak
 
Presentation of file handling in C language
Presentation of file handling in C languagePresentation of file handling in C language
Presentation of file handling in C languageShruthi48
 
File handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxFile handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxarmaansohail9356
 
File management
File managementFile management
File managementsumathiv9
 
File handling
File handlingFile handling
File handlingAns Ali
 
File Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptFile Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptRaja Ram Dutta
 
Python Files I_O17.pdf
Python Files I_O17.pdfPython Files I_O17.pdf
Python Files I_O17.pdfRashmiAngane1
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugevsol7206
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in CTushar B Kute
 

Similar to File handling in c (20)

Mesics lecture files in 'c'
Mesics lecture   files in 'c'Mesics lecture   files in 'c'
Mesics lecture files in 'c'
 
Presentation of file handling in C language
Presentation of file handling in C languagePresentation of file handling in C language
Presentation of file handling in C language
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
 
File handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxFile handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptx
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
 
Lecture 20 - File Handling
Lecture 20 - File HandlingLecture 20 - File Handling
Lecture 20 - File Handling
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
 
Unit 8
Unit 8Unit 8
Unit 8
 
File management
File managementFile management
File management
 
COM1407: File Processing
COM1407: File Processing COM1407: File Processing
COM1407: File Processing
 
File handling
File handlingFile handling
File handling
 
File Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptFile Handling as 08032021 (1).ppt
File Handling as 08032021 (1).ppt
 
Python Files I_O17.pdf
Python Files I_O17.pdfPython Files I_O17.pdf
Python Files I_O17.pdf
 
Module 5 file cp
Module 5 file cpModule 5 file cp
Module 5 file cp
 
File Handling in C
File Handling in CFile Handling in C
File Handling in C
 
Python file handlings
Python file handlingsPython file handlings
Python file handlings
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
 
file_c.pdf
file_c.pdffile_c.pdf
file_c.pdf
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in C
 
File management
File managementFile management
File management
 

More from David Livingston J

Performing Addition and Subtraction on Integers
Performing Addition and Subtraction on IntegersPerforming Addition and Subtraction on Integers
Performing Addition and Subtraction on IntegersDavid Livingston J
 
Introduction to Bluetooth technology
Introduction to Bluetooth technologyIntroduction to Bluetooth technology
Introduction to Bluetooth technologyDavid Livingston J
 
Past, Present and Future of Mobile Computing
Past, Present and Future of Mobile ComputingPast, Present and Future of Mobile Computing
Past, Present and Future of Mobile ComputingDavid Livingston J
 
Introduction & history of mobile computing
Introduction & history of mobile computingIntroduction & history of mobile computing
Introduction & history of mobile computingDavid Livingston J
 
Frequently asked questions in c
Frequently asked questions in cFrequently asked questions in c
Frequently asked questions in cDavid Livingston J
 
Frequently asked questions in c
Frequently asked questions in cFrequently asked questions in c
Frequently asked questions in cDavid Livingston J
 
Problem solving using Computer
Problem solving using ComputerProblem solving using Computer
Problem solving using ComputerDavid Livingston J
 

More from David Livingston J (9)

Performing Addition and Subtraction on Integers
Performing Addition and Subtraction on IntegersPerforming Addition and Subtraction on Integers
Performing Addition and Subtraction on Integers
 
Introduction to Bluetooth technology
Introduction to Bluetooth technologyIntroduction to Bluetooth technology
Introduction to Bluetooth technology
 
Wireless LAN Technoloy
Wireless LAN TechnoloyWireless LAN Technoloy
Wireless LAN Technoloy
 
Past, Present and Future of Mobile Computing
Past, Present and Future of Mobile ComputingPast, Present and Future of Mobile Computing
Past, Present and Future of Mobile Computing
 
Introduction & history of mobile computing
Introduction & history of mobile computingIntroduction & history of mobile computing
Introduction & history of mobile computing
 
Frequently asked questions in c
Frequently asked questions in cFrequently asked questions in c
Frequently asked questions in c
 
Frequently asked questions in c
Frequently asked questions in cFrequently asked questions in c
Frequently asked questions in c
 
Structure of a C program
Structure of a C programStructure of a C program
Structure of a C program
 
Problem solving using Computer
Problem solving using ComputerProblem solving using Computer
Problem solving using Computer
 

Recently uploaded

Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 

Recently uploaded (20)

Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 

File handling in c

  • 1. Developed by www.futureforyou.net & www.eshikshak.co.in
  • 2.  A collection of data or information that are stored on a computer known as file  A file is a collection of bytes stored on a secondary storage device.  There are four different types of file  Data files  Text files  Program files  Directory files  Different types of file store different types of information
  • 3.  A file has a beginning and an end.  We need a marker to mark the current position of the file from the beginning (in terms of bytes) while reading and write operation, takes place on a file.  Initially the marker is at the beginning of the file. We can move the marker to any other position in the file.  The new current position can be specified as an offset from the beginning the file.
  • 4.  A stream refers to the flow of data (in bytes) from one place to another (from program to file or vice-versa).  There are two types of streams  Text Stream ▪ It consists of sequence of characters ▪ Each line of characters in the stream may be terminated by a newline character. ▪ Text streams are used for textual data, which has a consistent appearance from one environment to another or from one machine to another
  • 5.  Binary Stream ▪ It is a series of bytes. ▪ Binary streams are primarily used for non-textual data, which is required to keep exact contents of the file.
  • 6.
  • 7.  A text file can be a stream of characters that a computer can process sequentially.  It is processed only in forward direction.  It is opened for one kind of operation (reading, writing, or appending) at any give time.  We can read only one character at a time from a text file.
  • 8.  A binary file is a file consisting of collection of bytes.  A binary file is also referred to as a character stream
  • 9.
  • 10.
  • 11.  A file is identified by its name.  This name is divided into two parts  File Name ▪ It consists of alphabets and digits. ▪ Special characters are also supported, but it depends on the operating system we use.  Extension ▪ It describes the file type
  • 12.  Before opening a file, we need to declare a file pointer. A file pointer is a pointer variable of type FILE, which is defined in the “stdio.h” header file.  A file pointer has the complete information about file being opened and processed such as:  Name of file, mode it is opened in, starting buffer address, a character pointer that points to the character being read.
  • 13.  To perform any operation (read or write) on a file, the file must be brought into memory from the storage device (hard disk).  This process of bringing the copy of the file from disk (secondary storage) to memory (main storage) is called opening the file.
  • 14. Mode Meaning r  Open a text file for reading only. If the file doesn’t exist, it returns null. w  Opens a file for writing only.  If file exists, than all the contents of that file are destroyed and new fresh blank file is copied on the disk and memory with same name  If file dosen’t exists, a new blank file is created and opened for writing.  Returns NULL if it is unable to open the file a  Appends to the existing text file  Adds data at the end of the file.  If file doesn’t exists then a new file is created.  Returns NULL if it is unable to open the file. rb  Open a binary file for reading wb  Open a binary file for reading ab  Append to a binary file r+  Open a text file for read/write w+  Opens the existing text file or Creates a text file for read/write
  • 15. Mode Meaning a+  Append or create a text file for read/write r+b  Open a binary file for read/write w+b  Create a binary file for read/write a+b  Append a binary file for read/write
  • 16.  fopen() function, like all the other file-system functions, uses the head file stdio.h  The name of the file to be opened is pointed to by fname  The string given as the second parameter - for mode, determines how the file should be accessed (r-read, w-write a-append).
  • 17. FILE *fp; if(fp = fopen(“myfile”,”r”)) == NULL) { printf(“Error opening a file”); exit(1); }
  • 18.  To read contents from an existing file, we need to open that file in read mode that means “r” mode  Algorithm to read data from a file: 1. Open the file in read mode 2. Read data from the file 3. Write the data into an output device 4. Repeat steps 3 and 4 untill the end of file occurs 5. Stop procedure
  • 19. #include<stdio.h> void main() { FILE *fp; char ch; fp=fopen(“clear.c”,”r”); if(fp==NULL) print(“Unable to open clear.c”); else { do { ch = getc(fp); putchar(ch); }while(ch!=EOF); fclose(fp); } }
  • 20.  Generally, a file contains a large amount of data.  In a large file, it is difficult to detect the end of file while reading.  In order to mark the end of a text file, a special character EOF is stored at the end.
  • 21.  To close a file and dis-associate it with a stream (file pointer), use fclose() function.  fclose() returns 0 if the file is closed successfully  The fcloseall() closes all the files opened previously.
  • 22. #include<stdio.h> void main() { FILE *fp; char ch; fp=fopen(“clear.c”,”r”); if(fp==NULL) print(“Unable to open clear.c”); else { do { ch = getc(fp);// gets the character from file putchar(ch); }while(ch!=EOF); fclose(fp); } }
  • 23.  We can add contents to an existing file whenever required.  Perform the following steps to append an existing file: 1. Declare a file pointer 2. Open the file in append mode 3. Read data from the keyboard 4. Write it into the file 5. Repeat steps 3 and 4 according to until the user gives input 6. Stop the process
  • 24.  char *fgets(char *str, int n, FILE *fptr);  This function reads a character from the file stream pointed by fptr and stores it in the character array ‘str’ until a new line character (n) is read or end of file (EOF) is reached or n-1 characters have been read.  fputs(const char *str, FILE *fptr);  This function writes data to the stream pointed to by fptr, the content of the string stored in ‘str’
  • 25. #include<stdio.h> void main() { FILE *fp; char line[280];int ch, i=0; fp=fopen(“a.dat”,”a”); if(fp==NULL) print(“Unable to open clear.c”); else{ do{ do{ line[i++] = getchar(); }while(line[i-1]!=‘*’); fputs(line, fp);//Writes string to the file i=0; printf(“nPress 1 to continue”); scanf(“%d”,&ch); }while(ch==1); fclose(fp); printf(“File is successfully created”); }
  • 26.  A file can be accessed in two ways:  Serial access  Random access  Generally all the text files are considered to be sequential files because lines of text (also called records) are stored in a file  The beginning of each record in a sequential file is unpredictable  Whereas, in random access files, all the records are in same length.
  • 27.  To modify the content of a file, open the file with read and write mode (“r+” or “w+” or “a+”)  Generally “r+” mode is used for both reading and writing operation. The procedure is as follows: 1. Initialize a pointer variable 2. Open the file in read and write mode 3. Read data from file and Print it 4. Move the file pointer to the place where we have the data to be modified and re-write the new data in that place. 5. Repeat steps 3 and 4 till the end of file reaches. 6. Stop the Process
  • 28. #include<stdio.h> struct stock { int itid, qty; char n[100]; float rate; }it; void main() { FILE *fp; int ch; int r = 0; fp = fopen(“item.c”, “r+”); if(fp==NULL) { printf(“Unable to open item.c”); } }
  • 29. else{ do{ fread(&it, sizeof(it),1,fp); printf(“n%d %s %d %f”, it.itid, it.n, it.qty, it.rate); printf(“n Press 1 to change it?”); scanf(“%d”,&ch); if(ch==1) { printf(“n Enter Itemid ItemName Quantity & Price”); scanf(“%d%s%d%f”, &it.itid, it.n, &it.qty, &it.rate); fseek(fp, r*sizeof(it), 0); fwrite(&it, sizeof(it),1,fp); }r++; }while(!feof(fp)); fclose(fp); } }
  • 30. fseek(FILE *fptr, long offset, int reference)  Moves the pointer from one record to another.  The first argument is the file pointer  The second argument tells the compiler how many bytes (offset) the pointer should be moved from a particular position.  The third argument is the reference from where the pointer should be moved n bytes (specified in the offset).
  • 31. fseek(FILE *fptr, long offset, int reference)  The third argument is the reference from where the pointer should be moved n bytes as specified in the offset.  SEEK_END moves the pointer from the end marker  SEEK_CUR moves the pointer from the current position  SEEK_SET moves the pointer from the beginning of the file
  • 32. fseek(FILE *fptr, long offset, int reference)  Example  fseek(fptr, size, SEEK_CUR) sets the cursor ahead from current position by size bytes  fseek(fptr, -size, SEEK_CUR) sets the cursor back from current position by size bytes  fseek(fptr, 0, SEEK_END) sets cursor to the end of the file  fseek(fptr, 0, SEEK_SET) sets cursor to the beginning of the file