SlideShare a Scribd company logo
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.
File handling in c
 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
File handling in c
File handling in c
 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
Ad

More Related Content

What's hot (20)

Function in C program
Function in C programFunction in C program
Function in C program
Nurul Zakiah Zamri Tan
 
structure and union
structure and unionstructure and union
structure and union
student
 
Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programming
avikdhupar
 
Functions in C
Functions in CFunctions in C
Functions in C
Kamal Acharya
 
Programming in C Presentation upto FILE
Programming in C Presentation upto FILEProgramming in C Presentation upto FILE
Programming in C Presentation upto FILE
Dipta Saha
 
Structures in c language
Structures in c languageStructures in c language
Structures in c language
tanmaymodi4
 
Call by value
Call by valueCall by value
Call by value
Dharani G
 
Variables in C Programming
Variables in C ProgrammingVariables in C Programming
Variables in C Programming
programming9
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
HalaiHansaika
 
SPL 9 | Scope of Variables in C
SPL 9 | Scope of Variables in CSPL 9 | Scope of Variables in C
SPL 9 | Scope of Variables in C
Mohammad Imam Hossain
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Strings in C
Strings in CStrings in C
Strings in C
Kamal Acharya
 
Operators in java
Operators in javaOperators in java
Operators in java
Then Murugeshwari
 
Variables in C and C++ Language
Variables in C and C++ LanguageVariables in C and C++ Language
Variables in C and C++ Language
Way2itech
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
Vineeta Garg
 
Java program structure
Java program structureJava program structure
Java program structure
shalinikarunakaran1
 
C++ Overview PPT
C++ Overview PPTC++ Overview PPT
C++ Overview PPT
Thooyavan Venkatachalam
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
Ahmad Idrees
 
File handling in c
File handling in cFile handling in c
File handling in c
aakanksha s
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
Muhammad Waqas
 
structure and union
structure and unionstructure and union
structure and union
student
 
Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programming
avikdhupar
 
Programming in C Presentation upto FILE
Programming in C Presentation upto FILEProgramming in C Presentation upto FILE
Programming in C Presentation upto FILE
Dipta Saha
 
Structures in c language
Structures in c languageStructures in c language
Structures in c language
tanmaymodi4
 
Call by value
Call by valueCall by value
Call by value
Dharani G
 
Variables in C Programming
Variables in C ProgrammingVariables in C Programming
Variables in C Programming
programming9
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
HalaiHansaika
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Variables in C and C++ Language
Variables in C and C++ LanguageVariables in C and C++ Language
Variables in C and C++ Language
Way2itech
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
Ahmad Idrees
 
File handling in c
File handling in cFile handling in c
File handling in c
aakanksha s
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
Muhammad Waqas
 

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'
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 language
Shruthi48
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
Mehul Desai
 
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 hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxFile handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptx
armaansohail9356
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
yndaravind
 
Lecture 20 - File Handling
Lecture 20 - File HandlingLecture 20 - File Handling
Lecture 20 - File Handling
Md. Imran Hossain Showrov
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
Sandeepbhuma1
 
File handling-c
File handling-cFile handling-c
File handling-c
CGC Technical campus,Mohali
 
Unit 8
Unit 8Unit 8
Unit 8
Keerthi Mutyala
 
File management
File managementFile management
File management
sumathiv9
 
COM1407: File Processing
COM1407: File Processing COM1407: File Processing
COM1407: File Processing
Hemantha Kulathilake
 
file handling in c programming with file functions
file handling in c programming with file functionsfile handling in c programming with file functions
file handling in c programming with file functions
10300PEDDIKISHOR
 
File handling
File handlingFile handling
File handling
Ans Ali
 
File Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptFile Handling as 08032021 (1).ppt
File Handling as 08032021 (1).ppt
Raja Ram Dutta
 
Python Files I_O17.pdf
Python Files I_O17.pdfPython Files I_O17.pdf
Python Files I_O17.pdf
RashmiAngane1
 
Module 5 file cp
Module 5 file cpModule 5 file cp
Module 5 file cp
Amarjith C K
 
File Handling in C
File Handling in CFile Handling in C
File Handling in C
VrushaliSolanke
 
Python file handlings
Python file handlingsPython file handlings
Python file handlings
22261A1201ABDULMUQTA
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
vsol7206
 
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 language
Shruthi48
 
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 hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxFile handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptx
armaansohail9356
 
File management
File managementFile management
File management
sumathiv9
 
file handling in c programming with file functions
file handling in c programming with file functionsfile handling in c programming with file functions
file handling in c programming with file functions
10300PEDDIKISHOR
 
File handling
File handlingFile handling
File handling
Ans Ali
 
File Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptFile Handling as 08032021 (1).ppt
File Handling as 08032021 (1).ppt
Raja Ram Dutta
 
Python Files I_O17.pdf
Python Files I_O17.pdfPython Files I_O17.pdf
Python Files I_O17.pdf
RashmiAngane1
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
vsol7206
 
Ad

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
David Livingston J
 
Introduction to Bluetooth technology
Introduction to Bluetooth technologyIntroduction to Bluetooth technology
Introduction to Bluetooth technology
David Livingston J
 
Wireless LAN Technoloy
Wireless LAN TechnoloyWireless LAN Technoloy
Wireless LAN Technoloy
David 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 Computing
David Livingston J
 
Introduction & history of mobile computing
Introduction & history of mobile computingIntroduction & history of mobile computing
Introduction & history of mobile computing
David Livingston J
 
Frequently asked questions in c
Frequently asked questions in cFrequently asked questions in c
Frequently asked questions in c
David Livingston J
 
Frequently asked questions in c
Frequently asked questions in cFrequently asked questions in c
Frequently asked questions in c
David Livingston J
 
Structure of a C program
Structure of a C programStructure of a C program
Structure of a C program
David Livingston J
 
Problem solving using Computer
Problem solving using ComputerProblem solving using Computer
Problem solving using Computer
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 Integers
David Livingston J
 
Introduction to Bluetooth technology
Introduction to Bluetooth technologyIntroduction to Bluetooth technology
Introduction to Bluetooth technology
David 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 Computing
David Livingston J
 
Introduction & history of mobile computing
Introduction & history of mobile computingIntroduction & history of mobile computing
Introduction & history of mobile computing
David Livingston J
 
Frequently asked questions in c
Frequently asked questions in cFrequently asked questions in c
Frequently asked questions in c
David Livingston J
 
Frequently asked questions in c
Frequently asked questions in cFrequently asked questions in c
Frequently asked questions in c
David Livingston J
 
Problem solving using Computer
Problem solving using ComputerProblem solving using Computer
Problem solving using Computer
David Livingston J
 
Ad

Recently uploaded (20)

Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 

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.
  • 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
  • 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