SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Mais procurados

Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
Alok Kumar
 

Mais procurados (20)

File handling in c
File handling in cFile handling in c
File handling in c
 
Structure in C
Structure in CStructure in C
Structure in C
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
 
Structures in c language
Structures in c languageStructures in c language
Structures in c language
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Control statements in c
Control statements in cControl statements in c
Control statements in c
 
File Management in C
File Management in CFile Management in C
File Management in C
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Array Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayArray Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional array
 
Union in C programming
Union in C programmingUnion in C programming
Union in C programming
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
 
Files in c++
Files in c++Files in c++
Files in c++
 
File operations in c
File operations in cFile operations in c
File operations in c
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
 

Semelhante a File handling in c

Semelhante a 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
 

Mais de 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
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
+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@
 

Último (20)

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
 
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 Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
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
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
+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...
 

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