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

What's hot (20)

Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in c
 
Data types in python
Data types in pythonData types in python
Data types in python
 
File handling in C++
File handling in C++File handling in C++
File handling in C++
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Structures in c language
Structures in c languageStructures in c language
Structures in c language
 
Arrays
ArraysArrays
Arrays
 
File in c
File in cFile in c
File in c
 
Structure in C
Structure in CStructure in C
Structure in C
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
 
Python Control structures
Python Control structuresPython Control structures
Python Control structures
 
File in C Programming
File in C ProgrammingFile in C Programming
File in C Programming
 
Python Modules
Python ModulesPython Modules
Python Modules
 
C programing -Structure
C programing -StructureC programing -Structure
C programing -Structure
 
Array and string
Array and stringArray and string
Array and string
 
Union in C programming
Union in C programmingUnion in C programming
Union in C programming
 
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...
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
Python file handling
Python file handlingPython file handling
Python file handling
 

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
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
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
 

Recently uploaded

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
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduitsrknatarajan
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfKamal Acharya
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
(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
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesPrabhanshu Chaturvedi
 
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
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 

Recently uploaded (20)

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...
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
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
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
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 Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
(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...
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and Properties
 
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...
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 

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.