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

structure and union
structure and unionstructure and union
structure and union
student
 

What's hot (20)

C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
 
Strings in C
Strings in CStrings in C
Strings in C
 
File in C language
File in C languageFile in C language
File in C language
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
 
Array Of Pointers
Array Of PointersArray Of Pointers
Array Of Pointers
 
structure and union
structure and unionstructure and union
structure and union
 
File Management in C
File Management in CFile Management in C
File Management in C
 
Storage class in C Language
Storage class in C LanguageStorage class in C Language
Storage class in C Language
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
 
Operators in C Programming
Operators in C ProgrammingOperators in C Programming
Operators in C Programming
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
Presentation on pointer.
Presentation on pointer.Presentation on pointer.
Presentation on pointer.
 
String functions in C
String functions in CString functions in C
String functions in C
 
File operations in c
File operations in cFile operations in c
File operations in c
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
File handling in C
File handling in CFile handling in C
File handling in C
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
C pointer
C pointerC pointer
C pointer
 
Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++
 

Similar to File handling in c

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
 
File handling-c
File handling-cFile handling-c
File handling-c
 
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
 

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

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

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