SlideShare a Scribd company logo
1 of 25
File Handling in C
What is a File?
 A file is a collection of related data that a
computers treats as a single unit.
 Computers store files to secondary storage
so that the contents of files remain intact
when a computer shuts down.
 When a computer reads a file, it copies the
file from the storage device to memory;
when it writes to a file, it transfers data
from memory to the storage device.
 C uses a structure called FILEFILE (defined in
stdio.hstdio.h) to store the attributes of a file.
Steps in Processing a File
1. Create the stream via a pointer variable
using the FILEFILE structure:
FILE *p;FILE *p;
2. Open the file, associating the stream
name with the file name.
3. Read or write the data.
4. Close the file.
The basic file operations are
 fopen - open a file- specify how its opened
(read/write) and type (binary/text)
 fclose - close an opened file
 fread - read from a file
 fwrite - write to a file
 fseek/fsetpos - move a file pointer to
somewhere in a file.
 ftell/fgetpos - tell you where the file pointer
is located.
File Open Modes
More on File Open Modes
Additionally,
 r+ - open for reading and writing, start at
beginning
 w+ - open for reading and writing
(overwrite file)
 a+ - open for reading and writing
(append if file exists)
File Open
 The file open function (fopenfopen) serves
two purposes:
It makes the connection between the
physical file and the stream.
It creates “a program file structure to store
the information” C needs to process the file.
 Syntax:
filepointer=filepointer=fopen(“filename”,fopen(“filename”,
“mode”);“mode”);
More On fopen
 The file mode tells C how the
program will use the file.
 The filename indicates the system
name and location for the file.
 We assign the return value of fopenfopen
to our pointer variable:
spData = fopen(“MYFILE.TXT”, “w”);spData = fopen(“MYFILE.TXT”, “w”);
spData = fopen(“A:MYFILE.TXT”, “w”);spData = fopen(“A:MYFILE.TXT”, “w”);
More On fopen
Closing a File
 When we finish with a mode, we need to
close the file before ending the program
or beginning another mode with that
same file.
 To close a file, we use fclosefclose and the
pointer variable:
fclose(spData);fclose(spData);
fprintf()
Syntax:Syntax:
fprintf (fp,"string",variables);
Example:Example:
int i = 12;
float x = 2.356;
char ch = 's';
FILE *fp;
fp=fopen(“out.txt”,”w”);
fprintf (fp, "%d %f %c", i, x, ch);
fscanf()
Syntax:Syntax:
fscanf (fp,"string",identifiers);
Example:Example:
FILE *fp;
Fp=fopen(“input.txt”,”r”);
int i;
fscanf (fp,“%d",i);
getc()
Syntax:Syntax:
identifier = getc (file pointer);
Example:Example:
FILE *fp;
fp=fopen(“input.txt”,”r”);
char ch;
ch = getc (fp);
putc()
write a single character to the output file,
pointed to by fp.
Example:Example:
FILE *fp;
char ch;
putc (ch,fp);
End of File
 There are a number of ways to test for the end-of-file
condition. Another way is to use the value returned by
the fscanffscanf function:
FILE *fptr1;
int istatus ;
istatus = fscanf (fptr1, "%d", &var) ;
if ( istatus == feof(fptr1) )
{
printf ("End-of-file encountered.n”) ;
}
Reading and Writing Files
#include <stdio.h>
int main ( )
{
FILE *outfile, *infile ;
int b = 5, f ;
float a = 13.72, c = 6.68, e, g ;
outfile = fopen ("testdata", "w") ;
fprintf (outfile, “ %f %d %f ", a, b, c) ;
fclose (outfile) ;
infile = fopen ("testdata", "r") ;
fscanf (infile,"%f %d %f", &e, &f, &g) ;
printf (“ %f %d %f n ", a, b, c) ;
printf (“ %f %d %f n ", e, f, g) ;
}
Example
#include <stdio.h>
#include<conio.h>
void main()
{
char ch;
FILE *fp;
fp=fopen("out.txt","r");
while(!feof(fp))
{
ch=getc(fp);
printf("n%c",ch);
}
getch();
}
fread ()
Declaration:
size_t fread(void *ptr, size_t size, size_t n, FILEsize_t fread(void *ptr, size_t size, size_t n, FILE
*stream);*stream);
Remarks:
fread reads a specified number of equal-sized
data items from an input stream into a block.
ptr = Points to a block into which data is read
size = Length of each item read, in bytes
n = Number of items read
stream = file pointer
Example
Example:Example:
#include <stdio.h>
int main()
{
FILE *f;
char buffer[11];
if (f = fopen("fred.txt", “r”))
{
fread(buffer, 1, 10, f);
buffer[10] = 0;
fclose(f);
printf("first 10 characters of the file:n%sn", buffer);
}
return 0;
}
fwrite()
Declaration:
size_t fwrite(const void *ptr, size_t size, size_t n,size_t fwrite(const void *ptr, size_t size, size_t n,
FILE*stream);FILE*stream);
Remarks:
fwrite appends a specified number of equal-sized data items to
an output file.
ptr = Pointer to any object; the data written begins at ptrptr = Pointer to any object; the data written begins at ptr
size = Length of each item of datasize = Length of each item of data
n =Number of data items to be appendedn =Number of data items to be appended
stream = file pointerstream = file pointer
Example
Example:Example:
#include <stdio.h>
int main()
{
char a[10]={'1','2','3','4','5','6','7','8','9','a'};
FILE *fs;
fs=fopen("Project.txt","w");
fwrite(a,1,10,fs);
fclose(fs);
return 0;
}
fseek()
This function sets the file position indicator for the stream pointed to
by stream or you can say it seeks a specified place within a file and
modify it.
SEEK_SETSEEK_SET Seeks from beginning of fileSeeks from beginning of file
SEEK_CURSEEK_CUR Seeks from current positionSeeks from current position
SEEK_ENDSEEK_END Seeks from end of fileSeeks from end of file
Example:Example:
#include <stdio.h>
int main()
{
FILE * f;
f = fopen("myfile.txt", "w");
fputs("Hello World", f);
fseek(f, 6, SEEK_SET); SEEK_CUR, SEEK_END
fputs(" India", f);
fclose(f);
return 0;
}
ftell()
offset = ftell( file pointer );offset = ftell( file pointer );
"ftell" returns the current position for input or output on the file
#include <stdio.h>
int main(void)
{
FILE *stream;
stream = fopen("MYFILE.TXT", "w");
fprintf(stream, "This is a test");
printf("The file pointer is at byte %ldn", ftell(stream));
fclose(stream);
return 0;
}
THANK YOUTHANK YOU
Written By:Written By:
Syed Ans AliSyed Ans Ali

More Related Content

What's hot (20)

Lecture 20 - File Handling
Lecture 20 - File HandlingLecture 20 - File Handling
Lecture 20 - File Handling
 
File handling in 'C'
File handling in 'C'File handling in 'C'
File handling in 'C'
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in C
 
File operations in c
File operations in cFile operations in c
File operations in c
 
File in C Programming
File in C ProgrammingFile in C Programming
File in C Programming
 
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
 
file
filefile
file
 
File handling in c
File handling in cFile handling in c
File handling in c
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
File in C language
File in C languageFile in C language
File in C language
 
Unit5
Unit5Unit5
Unit5
 
File handling-c programming language
File handling-c programming languageFile handling-c programming language
File handling-c programming language
 
file management in c language
file management in c languagefile management in c language
file management in c language
 
File handling in C
File handling in CFile handling in C
File handling in C
 
File handling-dutt
File handling-duttFile handling-dutt
File handling-dutt
 
File handling in c
File  handling in cFile  handling in c
File handling in c
 
File Management in C
File Management in CFile Management in C
File Management in C
 
Understanding c file handling functions with examples
Understanding c file handling functions with examplesUnderstanding c file handling functions with examples
Understanding c file handling functions with examples
 
file handling1
file handling1file handling1
file handling1
 

Similar to File handling

Data Structure Using C - FILES
Data Structure Using C - FILESData Structure Using C - FILES
Data Structure Using C - FILESHarish Kamat
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfsangeeta borde
 
File management and handling by prabhakar
File management and handling by prabhakarFile management and handling by prabhakar
File management and handling by prabhakarPrabhakarPremUpreti
 
Files let you store data on secondary storage such as a hard disk so that you...
Files let you store data on secondary storage such as a hard disk so that you...Files let you store data on secondary storage such as a hard disk so that you...
Files let you store data on secondary storage such as a hard disk so that you...Bern Jamie
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfsudhakargeruganti
 
Mesics lecture files in 'c'
Mesics lecture   files in 'c'Mesics lecture   files in 'c'
Mesics lecture files in 'c'eShikshak
 
File handling in c
File handling in cFile handling in c
File handling in caakanksha s
 
Concept of file handling in c
Concept of file handling in cConcept of file handling in c
Concept of file handling in cMugdhaSharma11
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.pptyuvrajkeshri
 

Similar to File handling (20)

Unit 8
Unit 8Unit 8
Unit 8
 
File management
File managementFile management
File management
 
Data Structure Using C - FILES
Data Structure Using C - FILESData Structure Using C - FILES
Data Structure Using C - FILES
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
 
File management and handling by prabhakar
File management and handling by prabhakarFile management and handling by prabhakar
File management and handling by prabhakar
 
PPS-II UNIT-5 PPT.pptx
PPS-II  UNIT-5 PPT.pptxPPS-II  UNIT-5 PPT.pptx
PPS-II UNIT-5 PPT.pptx
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
 
Files let you store data on secondary storage such as a hard disk so that you...
Files let you store data on secondary storage such as a hard disk so that you...Files let you store data on secondary storage such as a hard disk so that you...
Files let you store data on secondary storage such as a hard disk so that you...
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
 
Unit5 C
Unit5 C Unit5 C
Unit5 C
 
Mesics lecture files in 'c'
Mesics lecture   files in 'c'Mesics lecture   files in 'c'
Mesics lecture files in 'c'
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Concept of file handling in c
Concept of file handling in cConcept of file handling in c
Concept of file handling in c
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
Module 5 file cp
Module 5 file cpModule 5 file cp
Module 5 file cp
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
 
File Organization
File OrganizationFile Organization
File Organization
 
File_Handling in C.ppt
File_Handling in C.pptFile_Handling in C.ppt
File_Handling in C.ppt
 
File_Handling in C.ppt
File_Handling in C.pptFile_Handling in C.ppt
File_Handling in C.ppt
 

More from Ans Ali

Project,ATM Project,Java Atm Project
Project,ATM Project,Java Atm ProjectProject,ATM Project,Java Atm Project
Project,ATM Project,Java Atm ProjectAns Ali
 
Sort techniques
Sort techniquesSort techniques
Sort techniquesAns Ali
 
Dbms quries
Dbms quriesDbms quries
Dbms quriesAns Ali
 
chap 2 Ex#1.1
chap 2 Ex#1.1chap 2 Ex#1.1
chap 2 Ex#1.1Ans Ali
 
Intro to computing
Intro to computingIntro to computing
Intro to computingAns Ali
 
MS-Commands
 MS-Commands MS-Commands
MS-CommandsAns Ali
 
Types of Arrays
Types of ArraysTypes of Arrays
Types of ArraysAns Ali
 
Into to programming fundamentals
Into to programming fundamentalsInto to programming fundamentals
Into to programming fundamentalsAns Ali
 

More from Ans Ali (8)

Project,ATM Project,Java Atm Project
Project,ATM Project,Java Atm ProjectProject,ATM Project,Java Atm Project
Project,ATM Project,Java Atm Project
 
Sort techniques
Sort techniquesSort techniques
Sort techniques
 
Dbms quries
Dbms quriesDbms quries
Dbms quries
 
chap 2 Ex#1.1
chap 2 Ex#1.1chap 2 Ex#1.1
chap 2 Ex#1.1
 
Intro to computing
Intro to computingIntro to computing
Intro to computing
 
MS-Commands
 MS-Commands MS-Commands
MS-Commands
 
Types of Arrays
Types of ArraysTypes of Arrays
Types of Arrays
 
Into to programming fundamentals
Into to programming fundamentalsInto to programming fundamentals
Into to programming fundamentals
 

Recently uploaded

General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxcallscotland1987
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 

Recently uploaded (20)

Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 

File handling

  • 2. What is a File?  A file is a collection of related data that a computers treats as a single unit.  Computers store files to secondary storage so that the contents of files remain intact when a computer shuts down.  When a computer reads a file, it copies the file from the storage device to memory; when it writes to a file, it transfers data from memory to the storage device.  C uses a structure called FILEFILE (defined in stdio.hstdio.h) to store the attributes of a file.
  • 3. Steps in Processing a File 1. Create the stream via a pointer variable using the FILEFILE structure: FILE *p;FILE *p; 2. Open the file, associating the stream name with the file name. 3. Read or write the data. 4. Close the file.
  • 4. The basic file operations are  fopen - open a file- specify how its opened (read/write) and type (binary/text)  fclose - close an opened file  fread - read from a file  fwrite - write to a file  fseek/fsetpos - move a file pointer to somewhere in a file.  ftell/fgetpos - tell you where the file pointer is located.
  • 6. More on File Open Modes
  • 7. Additionally,  r+ - open for reading and writing, start at beginning  w+ - open for reading and writing (overwrite file)  a+ - open for reading and writing (append if file exists)
  • 8. File Open  The file open function (fopenfopen) serves two purposes: It makes the connection between the physical file and the stream. It creates “a program file structure to store the information” C needs to process the file.  Syntax: filepointer=filepointer=fopen(“filename”,fopen(“filename”, “mode”);“mode”);
  • 9. More On fopen  The file mode tells C how the program will use the file.  The filename indicates the system name and location for the file.  We assign the return value of fopenfopen to our pointer variable: spData = fopen(“MYFILE.TXT”, “w”);spData = fopen(“MYFILE.TXT”, “w”); spData = fopen(“A:MYFILE.TXT”, “w”);spData = fopen(“A:MYFILE.TXT”, “w”);
  • 11. Closing a File  When we finish with a mode, we need to close the file before ending the program or beginning another mode with that same file.  To close a file, we use fclosefclose and the pointer variable: fclose(spData);fclose(spData);
  • 12. fprintf() Syntax:Syntax: fprintf (fp,"string",variables); Example:Example: int i = 12; float x = 2.356; char ch = 's'; FILE *fp; fp=fopen(“out.txt”,”w”); fprintf (fp, "%d %f %c", i, x, ch);
  • 14. getc() Syntax:Syntax: identifier = getc (file pointer); Example:Example: FILE *fp; fp=fopen(“input.txt”,”r”); char ch; ch = getc (fp);
  • 15. putc() write a single character to the output file, pointed to by fp. Example:Example: FILE *fp; char ch; putc (ch,fp);
  • 16. End of File  There are a number of ways to test for the end-of-file condition. Another way is to use the value returned by the fscanffscanf function: FILE *fptr1; int istatus ; istatus = fscanf (fptr1, "%d", &var) ; if ( istatus == feof(fptr1) ) { printf ("End-of-file encountered.n”) ; }
  • 17. Reading and Writing Files #include <stdio.h> int main ( ) { FILE *outfile, *infile ; int b = 5, f ; float a = 13.72, c = 6.68, e, g ; outfile = fopen ("testdata", "w") ; fprintf (outfile, “ %f %d %f ", a, b, c) ; fclose (outfile) ; infile = fopen ("testdata", "r") ; fscanf (infile,"%f %d %f", &e, &f, &g) ; printf (“ %f %d %f n ", a, b, c) ; printf (“ %f %d %f n ", e, f, g) ; }
  • 18. Example #include <stdio.h> #include<conio.h> void main() { char ch; FILE *fp; fp=fopen("out.txt","r"); while(!feof(fp)) { ch=getc(fp); printf("n%c",ch); } getch(); }
  • 19. fread () Declaration: size_t fread(void *ptr, size_t size, size_t n, FILEsize_t fread(void *ptr, size_t size, size_t n, FILE *stream);*stream); Remarks: fread reads a specified number of equal-sized data items from an input stream into a block. ptr = Points to a block into which data is read size = Length of each item read, in bytes n = Number of items read stream = file pointer
  • 20. Example Example:Example: #include <stdio.h> int main() { FILE *f; char buffer[11]; if (f = fopen("fred.txt", “r”)) { fread(buffer, 1, 10, f); buffer[10] = 0; fclose(f); printf("first 10 characters of the file:n%sn", buffer); } return 0; }
  • 21. fwrite() Declaration: size_t fwrite(const void *ptr, size_t size, size_t n,size_t fwrite(const void *ptr, size_t size, size_t n, FILE*stream);FILE*stream); Remarks: fwrite appends a specified number of equal-sized data items to an output file. ptr = Pointer to any object; the data written begins at ptrptr = Pointer to any object; the data written begins at ptr size = Length of each item of datasize = Length of each item of data n =Number of data items to be appendedn =Number of data items to be appended stream = file pointerstream = file pointer
  • 22. Example Example:Example: #include <stdio.h> int main() { char a[10]={'1','2','3','4','5','6','7','8','9','a'}; FILE *fs; fs=fopen("Project.txt","w"); fwrite(a,1,10,fs); fclose(fs); return 0; }
  • 23. fseek() This function sets the file position indicator for the stream pointed to by stream or you can say it seeks a specified place within a file and modify it. SEEK_SETSEEK_SET Seeks from beginning of fileSeeks from beginning of file SEEK_CURSEEK_CUR Seeks from current positionSeeks from current position SEEK_ENDSEEK_END Seeks from end of fileSeeks from end of file Example:Example: #include <stdio.h> int main() { FILE * f; f = fopen("myfile.txt", "w"); fputs("Hello World", f); fseek(f, 6, SEEK_SET); SEEK_CUR, SEEK_END fputs(" India", f); fclose(f); return 0; }
  • 24. ftell() offset = ftell( file pointer );offset = ftell( file pointer ); "ftell" returns the current position for input or output on the file #include <stdio.h> int main(void) { FILE *stream; stream = fopen("MYFILE.TXT", "w"); fprintf(stream, "This is a test"); printf("The file pointer is at byte %ldn", ftell(stream)); fclose(stream); return 0; }
  • 25. THANK YOUTHANK YOU Written By:Written By: Syed Ans AliSyed Ans Ali