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)

Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Function in C
Function in CFunction in C
Function in C
 
Python reading and writing files
Python reading and writing filesPython reading and writing files
Python reading and writing files
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpp
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
 
Inline function
Inline functionInline function
Inline function
 
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
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
 
structure and union
structure and unionstructure and union
structure and union
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
File Handling In C++
File Handling In C++File Handling In C++
File Handling In C++
 
file pointers & manipulators.pptx
file pointers & manipulators.pptxfile pointers & manipulators.pptx
file pointers & manipulators.pptx
 
Managing input and output operation in c
Managing input and output operation in cManaging input and output operation in c
Managing input and output operation in c
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Union in C programming
Union in C programmingUnion in C programming
Union in C programming
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
 

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
 
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
 
file handling1
file handling1file handling1
file handling1
 

Recently uploaded

Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
Analog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAnalog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAbhinavSharma374939
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 

Recently uploaded (20)

Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
Analog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAnalog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog Converter
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 

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.