SlideShare a Scribd company logo
File handling in c
 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.
File handling in c
 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
File handling in c
 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();
}
File handling in c
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.
File handling in c
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

PPTX
File handling in C
Kamal Acharya
 
PPT
File handling-c
CGC Technical campus,Mohali
 
DOC
Arrays and Strings
Dr.Subha Krishna
 
PPTX
File in C language
Manash Kumar Mondal
 
PPTX
Union in C programming
Kamal Acharya
 
PDF
Character Array and String
Tasnima Hamid
 
PPT
Strings in c
vampugani
 
PPTX
Storage classes in C
Nitesh Bichwani
 
File handling in C
Kamal Acharya
 
Arrays and Strings
Dr.Subha Krishna
 
File in C language
Manash Kumar Mondal
 
Union in C programming
Kamal Acharya
 
Character Array and String
Tasnima Hamid
 
Strings in c
vampugani
 
Storage classes in C
Nitesh Bichwani
 

What's hot (20)

PPT
RECURSION IN C
v_jk
 
PPT
File handling in c
David Livingston J
 
PPTX
File Management in C
Paurav Shah
 
PDF
Pointers in C
Monishkanungo
 
PPTX
Pointer arithmetic in c
sangrampatil81
 
PPTX
Presentation on pointer.
Md. Afif Al Mamun
 
PPT
File in c
Prabhu Govind
 
PPTX
C Programming Unit-5
Vikram Nandini
 
PPTX
Pointer in c
lavanya marichamy
 
PPSX
Files in c++
Selvin Josy Bai Somu
 
PPTX
Pointers in c language
Tanmay Modi
 
PPT
File handling in C++
Hitesh Kumar
 
PPT
Class and object in C++
rprajat007
 
PPTX
Strings in C language
P M Patil
 
PPTX
Function in C program
Nurul Zakiah Zamri Tan
 
PPTX
C string
University of Potsdam
 
PPTX
Pointers in c++
Vineeta Garg
 
PPTX
Pointers in c - Mohammad Salman
MohammadSalman129
 
PPT
Memory allocation in c
Prabhu Govind
 
PPTX
Stream classes in C++
Shyam Gupta
 
RECURSION IN C
v_jk
 
File handling in c
David Livingston J
 
File Management in C
Paurav Shah
 
Pointers in C
Monishkanungo
 
Pointer arithmetic in c
sangrampatil81
 
Presentation on pointer.
Md. Afif Al Mamun
 
File in c
Prabhu Govind
 
C Programming Unit-5
Vikram Nandini
 
Pointer in c
lavanya marichamy
 
Files in c++
Selvin Josy Bai Somu
 
Pointers in c language
Tanmay Modi
 
File handling in C++
Hitesh Kumar
 
Class and object in C++
rprajat007
 
Strings in C language
P M Patil
 
Function in C program
Nurul Zakiah Zamri Tan
 
Pointers in c++
Vineeta Garg
 
Pointers in c - Mohammad Salman
MohammadSalman129
 
Memory allocation in c
Prabhu Govind
 
Stream classes in C++
Shyam Gupta
 
Ad

Viewers also liked (6)

PPT
File handling in c
Vikash Dhal
 
PPT
File handling in 'C'
Gaurav Garg
 
PPTX
UNIT 10. Files and file handling in C
Ashim Lamichhane
 
PPT
File in C Programming
Sonya Akter Rupa
 
PPSX
INTRODUCTION TO C PROGRAMMING
Abhishek Dwivedi
 
File handling in c
Vikash Dhal
 
File handling in 'C'
Gaurav Garg
 
UNIT 10. Files and file handling in C
Ashim Lamichhane
 
File in C Programming
Sonya Akter Rupa
 
INTRODUCTION TO C PROGRAMMING
Abhishek Dwivedi
 
Ad

Similar to File handling in c (20)

PPTX
want to learn files,then just use this ppt to learn
nalluribalaji157
 
PPTX
File Handling ppt.pptx shjd dbkd z bdjdb d
ssusere1e8b7
 
PPTX
File Handling in C Programming for Beginners
VSKAMCSPSGCT
 
PPT
C-Programming Chapter 5 File-handling-C.ppt
ssuserad38541
 
PPT
File handling-dutt
Anil Dutt
 
PPTX
C-Programming File-handling-C.pptx
SKUP1
 
PPTX
C-Programming File-handling-C.pptx
LECO9
 
PPTX
PPS PPT 2.pptx
Sandeepbhuma1
 
PPT
C-Programming Chapter 5 File-handling-C.ppt
sahakrishnan
 
PDF
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
sangeeta borde
 
PPT
Mesics lecture files in 'c'
eShikshak
 
PPT
Unit5
mrecedu
 
PPTX
File management
lalithambiga kamaraj
 
PDF
14. fiile io
웅식 전
 
PPT
file_handling_in_c.ppt
yuvrajkeshri
 
PPT
Files_in_C.ppt
kasthurimukila
 
PPSX
File mangement
Jigarthacker
 
DOCX
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
Rajeshkumar Reddy
 
DOCX
Unit 8
Keerthi Mutyala
 
DOCX
Understanding c file handling functions with examples
Muhammed Thanveer M
 
want to learn files,then just use this ppt to learn
nalluribalaji157
 
File Handling ppt.pptx shjd dbkd z bdjdb d
ssusere1e8b7
 
File Handling in C Programming for Beginners
VSKAMCSPSGCT
 
C-Programming Chapter 5 File-handling-C.ppt
ssuserad38541
 
File handling-dutt
Anil Dutt
 
C-Programming File-handling-C.pptx
SKUP1
 
C-Programming File-handling-C.pptx
LECO9
 
PPS PPT 2.pptx
Sandeepbhuma1
 
C-Programming Chapter 5 File-handling-C.ppt
sahakrishnan
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
sangeeta borde
 
Mesics lecture files in 'c'
eShikshak
 
Unit5
mrecedu
 
File management
lalithambiga kamaraj
 
14. fiile io
웅식 전
 
file_handling_in_c.ppt
yuvrajkeshri
 
Files_in_C.ppt
kasthurimukila
 
File mangement
Jigarthacker
 
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
Rajeshkumar Reddy
 
Understanding c file handling functions with examples
Muhammed Thanveer M
 

Recently uploaded (20)

PPTX
Fluid Mechanics, Module 3: Basics of Fluid Mechanics
Dr. Rahul Kumar
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PPTX
ANIMAL INTERVENTION WARNING SYSTEM (4).pptx
dodultrongaming
 
PDF
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
PDF
dse_final_merit_2025_26 gtgfffffcjjjuuyy
rushabhjain127
 
PPTX
Edge to Cloud Protocol HTTP WEBSOCKET MQTT-SN MQTT.pptx
dhanashri894551
 
PPTX
MSME 4.0 Template idea hackathon pdf to understand
alaudeenaarish
 
PPTX
AgentX UiPath Community Webinar series - Delhi
RohitRadhakrishnan8
 
PPTX
database slide on modern techniques for optimizing database queries.pptx
aky52024
 
PPTX
Production of bioplastic from fruit peels.pptx
alwingeorgealwingeor
 
PPT
SCOPE_~1- technology of green house and poyhouse
bala464780
 
PDF
Queuing formulas to evaluate throughputs and servers
gptshubham
 
PPTX
MET 305 MODULE 1 KTU 2019 SCHEME 25.pptx
VinayB68
 
PPTX
Simulation of electric circuit laws using tinkercad.pptx
VidhyaH3
 
PPTX
easa module 3 funtamental electronics.pptx
tryanothert7
 
PPTX
Module2 Data Base Design- ER and NF.pptx
gomathisankariv2
 
PDF
flutter Launcher Icons, Splash Screens & Fonts
Ahmed Mohamed
 
PDF
BRKDCN-2613.pdf Cisco AI DC NVIDIA presentation
demidovs1
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PDF
July 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
Fluid Mechanics, Module 3: Basics of Fluid Mechanics
Dr. Rahul Kumar
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
ANIMAL INTERVENTION WARNING SYSTEM (4).pptx
dodultrongaming
 
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
dse_final_merit_2025_26 gtgfffffcjjjuuyy
rushabhjain127
 
Edge to Cloud Protocol HTTP WEBSOCKET MQTT-SN MQTT.pptx
dhanashri894551
 
MSME 4.0 Template idea hackathon pdf to understand
alaudeenaarish
 
AgentX UiPath Community Webinar series - Delhi
RohitRadhakrishnan8
 
database slide on modern techniques for optimizing database queries.pptx
aky52024
 
Production of bioplastic from fruit peels.pptx
alwingeorgealwingeor
 
SCOPE_~1- technology of green house and poyhouse
bala464780
 
Queuing formulas to evaluate throughputs and servers
gptshubham
 
MET 305 MODULE 1 KTU 2019 SCHEME 25.pptx
VinayB68
 
Simulation of electric circuit laws using tinkercad.pptx
VidhyaH3
 
easa module 3 funtamental electronics.pptx
tryanothert7
 
Module2 Data Base Design- ER and NF.pptx
gomathisankariv2
 
flutter Launcher Icons, Splash Screens & Fonts
Ahmed Mohamed
 
BRKDCN-2613.pdf Cisco AI DC NVIDIA presentation
demidovs1
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
July 2025: Top 10 Read Articles Advanced Information Technology
ijait
 

File handling in c

  • 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.
  • 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
  • 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(); }
  • 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.
  • 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.