SlideShare a Scribd company logo
1 of 34
 File is a sequence of bits, bytes, lines or records whose meaning is defined by its
creator and user i.e. file is a collection of related data that a computers treats as a
single unit.
 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.
 FILE HANDLING in C programming uses FILE STREAM as a means of
communication between programs and data files.
 The INPUT STREAM extracts the data from the files and supplies it to the
program
 The OUTPUT STREAM stores the data into the file supplied by the program
The header file used for file handling is
<FSTREAM.H>
includes
IFSTREAM OFSTREAM
TO HANDLETHE INPUT FILES
It supports all the input operations
such as :
open(), get(), getline(),read(),
seekg(), tellg()
TO HANDLETHE OUTPUT FILES
It supports all the output operations
such as :
open(), put(), write(), seekp(), tellp()
Data files
 Can be created, updated, and processed by C programs
 Storage of data in variables and arrays is only temporary
Data files are of two types
TEXT FILES BINARY FILES
Saves the data in the form of ASCII
codes
It consist of sequential characters
divided into lines. Each line terminates
with the newline character (n).
Saves the data in Binary codes
It consist of data values such as
integers, floats or complex data types,
“using their memory representation.”
 Opening a file
 Reading data from a file
 Writing data to a file
 Closing a file
 ios::in open for reading
 ios::out open for writing
 ios::app writing contents at the eof
 ios::binary open as binary file
 ios::noreplace open fails if file already exist
 ios::nocreate open fails if file doesn’t exist
 ios::ate go to the eof at opening time
 ios::trunc truncate the file if it already exists
1. Create the stream via a pointer variable using
the FILE structure:
FILE *fp;
2. Open the file, associating the stream name
with the file name.
3. Read or write the data.
4. Close the file.
A file must be “opened” before it can be used.
FILE *fp;
fp = fopen (filename, mode);
fp = fopen (“myfile.dat”, “w”);
 fp is declared as a pointer to the data type FILE.
 filename is a string - specifies the name of the file.
 fopen returns a pointer to the file which is used in all
subsequent file operations.
 When you open a file you must also specify what
you wish to do with it i.e. Read from the file, Write
to the file, or both.
 You may use a number of different files in your
program. you must specify when reading or writing
which file you wish to use.This is accomplished by
using a variable called a file pointer.
 Every file you open has its own file pointer
variable. When you wish to write to a file you
specify the file by using its file pointer variable.
 You declare these file pointer variables as follows:
FILE *fp1, *fp2, *fp3;
 The variables fp1, fp2, fp3 are file pointers.You may use
any name you wish.
 A file pointer is simply a variable like an integer or
character. It does not point to a file or the data in a file. It is
simply used to indicate which file your I/O operation
refers to.
MODE is a string which specifies the purpose of opening the
file
 Read+ (r+) : It is an extension to the read mode. It opens a file for update.
Operations possible using this mode are reading the contents of an existing file,
writing new contents, modifying the existing ones. Returns NULL if file doesn’t
exist.
 Write+ (r+) : Similar to the write mode. It creates a file for update.
Operations that can be performed are write new contents and read and modify
the back
 Append+ (r+) :It opens or creates a file for update. Similar to append mode
and operations to be performed are read existing file, add new contents at the
end of the file. Cannot modify existing contents
 When we finish with a mode, we need to close the file before
ending the program or beginning another mode with that same file.
 Syntax : fclose (filepointer) ;
FILE *xyz ;
xyz = fopen (“test”, “w”) ;
…….
fclose (xyz) ;
#include<stdio.h>
#include<conio.h>
main()
{
FILE * fp;
fp=fopen(“abc.c”,”r”);
if(fp==NULL)
{ printf(“file cannot open”);
exit(1);
}
fclose(fp);
getch();
}
Functions for reading a character from a file are
 fgetc()
 getc()
syntax: ch = fgetc (fp) ;
ch = getc (fp) ;
It returns a character read from the file to which “fp” points to and
stores this value in the variable file to “ch”. The fp pointer then
automatically points to the next character in the file (char is of 1
byte)
THIS IS MY FIRST FILE
getw();
This functions is an integer oriented function.This is used for reading a
integer character from a file in which numbers are stored
syntax:: a = getw (fp) ;
The numbers read will be stored in the integer type variable “a”
and “fp” file pointer automatically moves forward by 2 bytes file
pointer (int is of 2 bytes). It uses binary mode.
fscanf();
Reads any type of variable i.e char, int, float, string etc. from the
file. It behaves similar to the console input function scanf , the only
difference it works with files.
syntax: fscanf ( fp , “ %c ” , &ch) ;
file pointer control string char type variable
If in case of “fp” we put “stdin” it would work similar to scanf();
fgets(); or gets();
This function is used to read strings from the file
syntax: fgets (str , n , fp) ;
It returns a string read upto n characters or upto the end of the
string i.e null character ‘0’.When all the lines from the file are read
and we attempt to read one more line, fgets() returns a null value.
Functions for writing a character or number in a file are
 fputc()
 putc()
syntax: putc ( ch , fp );
fputc ( ch , fp );
Both these functions write a character in the file at the position
specified by the pointer.The value of a variable ch is written in the
file by fp.
The fp pointer then automatically moves to the end of the
character after printing characters in the file, that next character
could be written on next position. It uses the file in the text mode.
putw();
This functions is an integer oriented function.This is used for
printing an integer character in a file.
syntax:: putw ( a , fp ) ;
The integer value of a is written in file by fp and then “fp” file
pointer automatically moves forward by 2 bytes file pointer (int is
of 2 bytes) and prints the next character. It uses binary mode.
fprintf();
Prints any type of variable i.e. char, int, float, string etc. in the file. It
behaves similar to the console input function printf , the only
difference it works with files.
syntax: fprintf ( fp , “ %d ” , ch) ;
file pointer control string char type variable
If in case of “fp” we put “stdout” it would work similar to printf();
fputs(); or puts();
This function is used to write strings in the file
syntax: fputs (str , fp) ;
fwrite();
It transfers a specified number of bytes beginning at a specified location in
memory to termed as a structure to a file.The data is written beginning at the
location in the file indicated by the file position pointer.
syntax:
fwrite( structure , size-of-structure , starting value , file pointer)
fwrite( &e , sizeof (e) , 1 , fp)
How to check EOF condition when using fscanf?
Use the function eof
if (eof (fp))
printf (“n Reached end of file”) ;
How to check successful open?
For opening in “r” mode, the file must exist.
if (fp == NULL)
printf (“n Unable to open file”) ;
While reading from a data file, if we want to read the
complete file i.e. till the end of data , then an end of file
marker should be checked.
 EOF :: EOF is a character and every character read from the file is
compared against this character.
while ( a = getc(fp) != eof )
putc ( a, f1 );
 feof(); :: feof() is a macro which returns 0 if end of file is not
reached. If end of file is reached it returns a non zero value.
if ( feof ( fp ) )
printf( “ the end of file is reached”);
void main()
{ FILE *fopen(), *fp;
int c ;
char filename[40] ;
printf(“Enter file to be displayed: “);
gets( filename ) ; // take in the filename as a string
fp = fopen( filename, “r”); // opens the file in read mode
c = getc( fp ) ; // reads the first character of the file
while ( c != EOF )
{ putc(c); //displays the character as it reads
c = getc ( fp );
}
fclose( fp );
}
NOTE: If the file is empty, we are at the end, so getc returns EOF
a special value to indicate that the end of file has been
reached. (Normally -1 is used for EOF)
Alternatively, you could prompt the user to enter the filename again, and try to
open it again:
fp = fopen (fname, “r”) ;
while ( fp == NULL)
{
printf(“Cannot open %s for reading n”, fname );
printf(“nnEnter filename :” );
gets( fname );
fp = fopen (fname, “r”) ;
}
 Read/Write functions in standard library
 fgetc
▪ Reads one character from a file
▪ Takes a FILE pointer as an argument
▪ fgetc( stdin ) equivalent to getchar()
 fputc
▪ Writes one character to a file
▪ Takes a FILE pointer and a character to write as an argument
▪ fputc( 'a', stdout ) equivalent to putchar( 'a' )
 fgets
▪ Reads a line from a file
 fputs
▪ Writes a line to a file
 fscanf / fprintf
▪ File processing equivalents of scanf and printf
32
main() {
FILE *in, *out ;
char c ;
in = fopen (“infile.dat”, “r”) ;
out = fopen (“outfile.dat”, “w”) ;
while ((c = getc (in)) != EOF)
putc (toupper (c), out);
fclose (in) ;
fclose (out) ;
}
Fputc();
If we want we can also print the contents from the file and directly
on the printer using fputc()
syntax: fputc (ch , stdprn) ;
Where stdprn is the standard file pointer used instead of user
defined file pointer. It means that the data should be written on the
printer and not on the file.
File handling in c

More Related Content

What's hot (20)

File operations in c
File operations in cFile operations in c
File operations in c
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
 
User defined functions in C
User defined functions in CUser defined functions in C
User defined functions in C
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
String functions in C
String functions in CString functions in C
String functions in C
 
Pointer to function 1
Pointer to function 1Pointer to function 1
Pointer to function 1
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
Call by value
Call by valueCall by value
Call by value
 
File in C language
File in C languageFile in C language
File in C language
 
Typecasting in c
Typecasting in cTypecasting in c
Typecasting in c
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
Types of function call
Types of function callTypes of function call
Types of function call
 
c++ programming Unit 2 basic structure of a c++ program
c++ programming Unit 2 basic structure of a c++ programc++ programming Unit 2 basic structure of a c++ program
c++ programming Unit 2 basic structure of a c++ program
 

Similar to File handling in c

Similar to File handling in c (20)

Unit 8
Unit 8Unit 8
Unit 8
 
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
 
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
File managementFile management
File management
 
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
 
Unit 5 dwqb ans
Unit 5 dwqb ansUnit 5 dwqb ans
Unit 5 dwqb ans
 
4 text file
4 text file4 text file
4 text file
 
UNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CUNIT 10. Files and file handling in C
UNIT 10. Files and file handling in C
 
Unit5 C
Unit5 C Unit5 C
Unit5 C
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
Satz1
Satz1Satz1
Satz1
 
Mesics lecture files in 'c'
Mesics lecture   files in 'c'Mesics lecture   files in 'c'
Mesics lecture files in 'c'
 
Handout#01
Handout#01Handout#01
Handout#01
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
 
Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10
 
Unit5
Unit5Unit5
Unit5
 
File handling C program
File handling C programFile handling C program
File handling C program
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
 
Programming in C
Programming in CProgramming in C
Programming in C
 

Recently uploaded

Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxJuliansyahHarahap1
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Arindam Chakraborty, Ph.D., P.E. (CA, TX)
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringmulugeta48
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityMorshed Ahmed Rahath
 
Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086anil_gaur
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoordharasingh5698
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTbhaskargani46
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projectssmsksolar
 
22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf203318pmpc
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueBhangaleSonal
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.Kamal Acharya
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 

Recently uploaded (20)

Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects
 
22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 

File handling in c

  • 1.
  • 2.  File is a sequence of bits, bytes, lines or records whose meaning is defined by its creator and user i.e. file is a collection of related data that a computers treats as a single unit.  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.  FILE HANDLING in C programming uses FILE STREAM as a means of communication between programs and data files.  The INPUT STREAM extracts the data from the files and supplies it to the program  The OUTPUT STREAM stores the data into the file supplied by the program
  • 3. The header file used for file handling is <FSTREAM.H> includes IFSTREAM OFSTREAM TO HANDLETHE INPUT FILES It supports all the input operations such as : open(), get(), getline(),read(), seekg(), tellg() TO HANDLETHE OUTPUT FILES It supports all the output operations such as : open(), put(), write(), seekp(), tellp()
  • 4. Data files  Can be created, updated, and processed by C programs  Storage of data in variables and arrays is only temporary Data files are of two types TEXT FILES BINARY FILES Saves the data in the form of ASCII codes It consist of sequential characters divided into lines. Each line terminates with the newline character (n). Saves the data in Binary codes It consist of data values such as integers, floats or complex data types, “using their memory representation.”
  • 5.  Opening a file  Reading data from a file  Writing data to a file  Closing a file
  • 6.  ios::in open for reading  ios::out open for writing  ios::app writing contents at the eof  ios::binary open as binary file  ios::noreplace open fails if file already exist  ios::nocreate open fails if file doesn’t exist  ios::ate go to the eof at opening time  ios::trunc truncate the file if it already exists
  • 7. 1. Create the stream via a pointer variable using the FILE structure: FILE *fp; 2. Open the file, associating the stream name with the file name. 3. Read or write the data. 4. Close the file.
  • 8. A file must be “opened” before it can be used. FILE *fp; fp = fopen (filename, mode); fp = fopen (“myfile.dat”, “w”);  fp is declared as a pointer to the data type FILE.  filename is a string - specifies the name of the file.  fopen returns a pointer to the file which is used in all subsequent file operations.
  • 9.
  • 10.  When you open a file you must also specify what you wish to do with it i.e. Read from the file, Write to the file, or both.  You may use a number of different files in your program. you must specify when reading or writing which file you wish to use.This is accomplished by using a variable called a file pointer.  Every file you open has its own file pointer variable. When you wish to write to a file you specify the file by using its file pointer variable.
  • 11.  You declare these file pointer variables as follows: FILE *fp1, *fp2, *fp3;  The variables fp1, fp2, fp3 are file pointers.You may use any name you wish.  A file pointer is simply a variable like an integer or character. It does not point to a file or the data in a file. It is simply used to indicate which file your I/O operation refers to.
  • 12. MODE is a string which specifies the purpose of opening the file
  • 13.
  • 14.  Read+ (r+) : It is an extension to the read mode. It opens a file for update. Operations possible using this mode are reading the contents of an existing file, writing new contents, modifying the existing ones. Returns NULL if file doesn’t exist.  Write+ (r+) : Similar to the write mode. It creates a file for update. Operations that can be performed are write new contents and read and modify the back  Append+ (r+) :It opens or creates a file for update. Similar to append mode and operations to be performed are read existing file, add new contents at the end of the file. Cannot modify existing contents
  • 15.  When we finish with a mode, we need to close the file before ending the program or beginning another mode with that same file.  Syntax : fclose (filepointer) ; FILE *xyz ; xyz = fopen (“test”, “w”) ; ……. fclose (xyz) ;
  • 16. #include<stdio.h> #include<conio.h> main() { FILE * fp; fp=fopen(“abc.c”,”r”); if(fp==NULL) { printf(“file cannot open”); exit(1); } fclose(fp); getch(); }
  • 17.
  • 18. Functions for reading a character from a file are  fgetc()  getc() syntax: ch = fgetc (fp) ; ch = getc (fp) ; It returns a character read from the file to which “fp” points to and stores this value in the variable file to “ch”. The fp pointer then automatically points to the next character in the file (char is of 1 byte) THIS IS MY FIRST FILE
  • 19. getw(); This functions is an integer oriented function.This is used for reading a integer character from a file in which numbers are stored syntax:: a = getw (fp) ; The numbers read will be stored in the integer type variable “a” and “fp” file pointer automatically moves forward by 2 bytes file pointer (int is of 2 bytes). It uses binary mode.
  • 20. fscanf(); Reads any type of variable i.e char, int, float, string etc. from the file. It behaves similar to the console input function scanf , the only difference it works with files. syntax: fscanf ( fp , “ %c ” , &ch) ; file pointer control string char type variable If in case of “fp” we put “stdin” it would work similar to scanf();
  • 21. fgets(); or gets(); This function is used to read strings from the file syntax: fgets (str , n , fp) ; It returns a string read upto n characters or upto the end of the string i.e null character ‘0’.When all the lines from the file are read and we attempt to read one more line, fgets() returns a null value.
  • 22.
  • 23. Functions for writing a character or number in a file are  fputc()  putc() syntax: putc ( ch , fp ); fputc ( ch , fp ); Both these functions write a character in the file at the position specified by the pointer.The value of a variable ch is written in the file by fp. The fp pointer then automatically moves to the end of the character after printing characters in the file, that next character could be written on next position. It uses the file in the text mode.
  • 24. putw(); This functions is an integer oriented function.This is used for printing an integer character in a file. syntax:: putw ( a , fp ) ; The integer value of a is written in file by fp and then “fp” file pointer automatically moves forward by 2 bytes file pointer (int is of 2 bytes) and prints the next character. It uses binary mode.
  • 25. fprintf(); Prints any type of variable i.e. char, int, float, string etc. in the file. It behaves similar to the console input function printf , the only difference it works with files. syntax: fprintf ( fp , “ %d ” , ch) ; file pointer control string char type variable If in case of “fp” we put “stdout” it would work similar to printf();
  • 26. fputs(); or puts(); This function is used to write strings in the file syntax: fputs (str , fp) ; fwrite(); It transfers a specified number of bytes beginning at a specified location in memory to termed as a structure to a file.The data is written beginning at the location in the file indicated by the file position pointer. syntax: fwrite( structure , size-of-structure , starting value , file pointer) fwrite( &e , sizeof (e) , 1 , fp)
  • 27. How to check EOF condition when using fscanf? Use the function eof if (eof (fp)) printf (“n Reached end of file”) ; How to check successful open? For opening in “r” mode, the file must exist. if (fp == NULL) printf (“n Unable to open file”) ;
  • 28. While reading from a data file, if we want to read the complete file i.e. till the end of data , then an end of file marker should be checked.  EOF :: EOF is a character and every character read from the file is compared against this character. while ( a = getc(fp) != eof ) putc ( a, f1 );  feof(); :: feof() is a macro which returns 0 if end of file is not reached. If end of file is reached it returns a non zero value. if ( feof ( fp ) ) printf( “ the end of file is reached”);
  • 29. void main() { FILE *fopen(), *fp; int c ; char filename[40] ; printf(“Enter file to be displayed: “); gets( filename ) ; // take in the filename as a string fp = fopen( filename, “r”); // opens the file in read mode c = getc( fp ) ; // reads the first character of the file while ( c != EOF ) { putc(c); //displays the character as it reads c = getc ( fp ); } fclose( fp ); }
  • 30. NOTE: If the file is empty, we are at the end, so getc returns EOF a special value to indicate that the end of file has been reached. (Normally -1 is used for EOF) Alternatively, you could prompt the user to enter the filename again, and try to open it again: fp = fopen (fname, “r”) ; while ( fp == NULL) { printf(“Cannot open %s for reading n”, fname ); printf(“nnEnter filename :” ); gets( fname ); fp = fopen (fname, “r”) ; }
  • 31.  Read/Write functions in standard library  fgetc ▪ Reads one character from a file ▪ Takes a FILE pointer as an argument ▪ fgetc( stdin ) equivalent to getchar()  fputc ▪ Writes one character to a file ▪ Takes a FILE pointer and a character to write as an argument ▪ fputc( 'a', stdout ) equivalent to putchar( 'a' )  fgets ▪ Reads a line from a file  fputs ▪ Writes a line to a file  fscanf / fprintf ▪ File processing equivalents of scanf and printf
  • 32. 32 main() { FILE *in, *out ; char c ; in = fopen (“infile.dat”, “r”) ; out = fopen (“outfile.dat”, “w”) ; while ((c = getc (in)) != EOF) putc (toupper (c), out); fclose (in) ; fclose (out) ; }
  • 33. Fputc(); If we want we can also print the contents from the file and directly on the printer using fputc() syntax: fputc (ch , stdprn) ; Where stdprn is the standard file pointer used instead of user defined file pointer. It means that the data should be written on the printer and not on the file.