SlideShare a Scribd company logo
2
Most read
4
Most read
5
Most read
Lecture By
Mr. Salunke R. B.
on
File Handling in C
Programming
To
Assistant Professor & Head,
Department of Computer Application,
Dada Patil Mahavidyalaya, Karjat,
Dist Ahmednagar, State Maharashtra
Topic
• File – Definition. Types of File, File Opening modes
• File Functions –
fopen(), fclose(), fgetc(), fputc(), fgets(),
fputs(), fscanf(), fprintf(), getw(), putw(),
fread(), fwrite(), fseek(),ftell() etc
• File Management –
Opening/Closing a File,
Input/Output operations on ,
Error Handling During I/O Operations,
Command Line Arguments
• Random Access File
File
• Definition-
ā€šA Collection of data or Information that are stored on computer
permanently known as File‛
• Types of files –
Text File
Binary File
• File Opening Modes –
Read- ā€šr‛ , Write-ā€šw‛, Append-ā€ša‛
• r – Opens a file in read mode and sets pointer to the first character
in the file. It returns null if file does not exist.
• w – Opens a file in write mode. It returns null if file could not be
opened. If file exists, data are overwritten.
• a – Opens a file in append mode. It returns null if file couldn’t be
opened.
File Functions
• fopen() – To open file
• fclose() – To close file
• fgetc() – To read character from file
• fputc() – To write or add character to file
• fgets() - To read string / line from file
• fputs() - To write string / line to file
• fscanf() – To scan data from file
• fprintf() – To write data into file
• getw() – To read Integer values from file
• putw() – To write Integer values to file
• fread() – To read character
• fwrite() – To write character
• fseek() – To read data
• ftell() – go to End of file
functions Description
fopen () fopen () function creates a new file or opens an existing file.
fclose () fclose () function closes an opened file.
getw () getw () function reads an integer from file.
putw () putw () functions writes an integer to file.
fgetc () fgetc () function reads a character from file.
fputc () fputc () functions write a character to file.
gets () gets () function reads line from keyboard.
puts () puts () function writes line to o/p screen.
fgets () fgets () function reads string from a file, one line at a time.
fputs () fputs () function writes string to a file.
feof () feof () function finds end of file.
fgetchar () fgetchar () function reads a character from keyboard.
fprintf () fprintf () function writes formatted data to a file.
fscanf () fscanf () function reads formatted data from a file.
fputchar ()
fputchar () function writes a character onto the output screen
from keyboard input.
fseek () fseek () function moves file pointer position to given location.
SEEK_SET
SEEK_SET moves file pointer position to the beginning of the
file.
SEEK_CUR SEEK_CUR moves file pointer position to given location.
SEEK_END SEEK_END moves file pointer position to the end of file.
ftell () ftell () function gives current position of file pointer.
rewind ()
rewind () function moves file pointer position to the
beginning of the file.
getc () getc () function reads character from file.
getch () getch () function reads character from keyboard.
getche ()
getche () function reads character from keyboard and
echoes to o/p screen.
getchar () getchar () function reads character from keyboard.
putc () putc () function writes a character to file.
putchar () putchar () function writes a character to screen.
printf () printf () function writes formatted data to screen.
sprinf () sprinf () function writes formatted output to string.
scanf () scanf () function reads formatted data from keyboard.
sscanf () sscanf () function Reads formatted input from a string.
remove () remove () function deletes a file.
fflush () fflush () function flushes a file.
1. EXAMPLE PROGRAM FOR FILE OPEN,
FILE WRITE AND FILE CLOSE
/ * Open, write and close a file : */
# include <stdio.h>
# include <string.h>
void main( )
{
FILE *fp ;
char data[50];
// opening an existing file
printf( "Opening the file test.c in write
mode" ) ;
fp = fopen("test.c", "w") ;
if ( fp == NULL )
{
printf( "Could not open file test.c" ) ;
return 1;
}
printf( "n Enter some text from keyboard‛

ā€š to write in the file test.c" ) ;
// getting input from user
while ( strlen ( gets( data ) ) > 0 )
{
// writing in the file
fputs(data, fp) ;
fputs("n", fp) ;
}
// closing the file
printf("Closing the file test.c") ;
fclose(fp) ;
getch();
}
Output
Opening the file test.c in write mode
Enter some text from keyboard to write
in the file test.c
Hai, How are you?
Closing the file test.c
File Management –
• Opening/Closing a File
• Input / Output operations on
• Error Handling During I/O Operations
• Command Line Arguments
Open File
• Declaration: FILE *fopen (const char *filename, const char *mode)
• fopen() function is used to open a file to perform operations such as
reading, writing etc. In a C program, we declare a file pointer and
use fopen() as below. fopen() function creates a new file if the
mentioned file name does not exist.
• FILE *fp;
fp=fopen (ā€šfilename‛, ā€›ā€˜mode‛);
• Where,
fp – file pointer to the data type ā€šFILE‛.
filename – the actual file name with full path of the file.
mode – refers to the operation that will be performed on the file.
Example: r, w, a, r+, w+ and a+. Please refer below the description
for these mode of operations.
Close File
• Declaration: int fclose(FILE *fp);
• fclose() function closes the file that is being pointed by
file pointer fp. In a C program, we close a file as below.
fclose (fp);
Read file - Line by Line
• Declaration: char *fgets(char *string, int n, FILE *fp)
• fgets function is used to read a file line by line. In a C
program, we use fgets function as below.
fgets (buffer, size, fp);
• where,
buffer – buffer to put the data in.
size – size of the buffer
fp – file pointer
Write into file
• Declaration:
int fprintf(FILE *fp, const char *format, …);fprintf()
function writes string into a file pointed by fp. In a C
program, we write string into a file as below.
fprintf (fp, ā€šsome data‛); or
fprintf (fp, ā€štext %d‛, variable_name);
Command Line Arguments in C
• The arguments passed from command line are called
command line arguments. These arguments are handled
by main() function.
• To support command line argument, you need to change
the structure of main() function as given below.
• int main(int argc, char *argv[] )
• Here, argc counts the number of arguments. It counts the
file name as the first argument.
• The argv[] contains the total number of arguments. The
first argument is the file name always.
Program
#include <stdio.h>
int main( int argc, char *argv[] )
{
if( argc == 2 )
{
printf("The argument supplied is %sn", argv[1]);
}
else if( argc > 2 )
{
printf("Too many arguments supplied.n");
}
else
{
printf("One argument expected.n");
}
}
You can run this program by
1. Go File Menu
2.Select Doss Shell Option
3. Type Program Name
4. and Type parameters
Random Access File
#include <stdio.h>
int main () {
FILE *fp;
int c;
fp = fopen("file.txt","w+");
fputs("This is study.com", fp);
// we are using fseek to shift the file //
pointer to the 7th position
fseek( fp, 7, SEEK_SET );
//Now we overwrite C programming // in
the 7th position
fputs(" C Programming", fp);
//now we print the current position of
// the file pointer using ftell
printf("The current position of the file
pointer is: %ldn", ftell(fp));
//we take the file pointer to the
// beginning of the file
rewind(fp);
//now we verify if rewind() worked
// using ftell
printf("The current position of the file
pointer is: %ldn", ftell(fp));
while(1)
{
c = fgetc(fp);
if( feof(fp) )
{
break;
}
printf("%c", c);
}
fclose(fp);
return(0);
}
• Output
The current position of the file pointer is: 21
The current position of the file pointer is: 0
This is C Programming
Any Queries ?
Thank you

More Related Content

PPSX
Files in c++
PPTX
File handling in c
PPT
File handling-c
PPTX
Typecasting in c
PPT
File handling in c
PPTX
PPTX
Data file handling in c++
PPTX
File Management in C
Files in c++
File handling in c
File handling-c
Typecasting in c
File handling in c
Data file handling in c++
File Management in C

What's hot (20)

PPTX
Encapsulation
PPTX
Queue Implementation Using Array & Linked List
Ā 
PPTX
Stream classes in C++
PPTX
Type casting in c programming
PPTX
File in C language
PPTX
C Programming Unit-5
PPTX
File handling in c language
PPTX
Set data structure
PPTX
Functions in C
PPTX
Constructor and Types of Constructors
PPTX
C++ compilation process
PPTX
Managing input and output operation in c
PPT
Graphs - Discrete Math
PPTX
2CPP09 - Encapsulation
PPTX
Templates in c++
PPTX
Header files of c++ unit 3 -topic 3
PPT
File in C Programming
PPTX
Call by value or call by reference in C++
Encapsulation
Queue Implementation Using Array & Linked List
Ā 
Stream classes in C++
Type casting in c programming
File in C language
C Programming Unit-5
File handling in c language
Set data structure
Functions in C
Constructor and Types of Constructors
C++ compilation process
Managing input and output operation in c
Graphs - Discrete Math
2CPP09 - Encapsulation
Templates in c++
Header files of c++ unit 3 -topic 3
File in C Programming
Call by value or call by reference in C++
Ad

Similar to File Handling in C Programming (20)

PDF
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
PDF
ppt5-190810161800 (1).pdf
PPTX
want to learn files,then just use this ppt to learn
PPTX
File Handling in C.pptx
PPTX
File handling in c
PDF
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
PPT
C-Programming Chapter 5 File-handling-C.ppt
PPTX
MODULE 8-File and preprocessor.pptx for c program learners easy learning
PPTX
pre processor and file handling in c language ppt
PPTX
File management
PPT
How to do file-handling - in C language
PPTX
Programming C- File Handling , File Operation
PPTX
File Handling ppt.pptx shjd dbkd z bdjdb d
PPT
C-Programming Chapter 5 File-handling-C.ppt
PPTX
C-Programming File-handling-C.pptx
Ā 
PPTX
C-Programming File-handling-C.pptx
Ā 
PPTX
File Handling in C
PDF
File Handling-Module V.pdf dSfcsvfsvcdfscfd
PPTX
File Handling in C Programming for Beginners
PDF
637225560972186380.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
ppt5-190810161800 (1).pdf
want to learn files,then just use this ppt to learn
File Handling in C.pptx
File handling in c
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
C-Programming Chapter 5 File-handling-C.ppt
MODULE 8-File and preprocessor.pptx for c program learners easy learning
pre processor and file handling in c language ppt
File management
How to do file-handling - in C language
Programming C- File Handling , File Operation
File Handling ppt.pptx shjd dbkd z bdjdb d
C-Programming Chapter 5 File-handling-C.ppt
C-Programming File-handling-C.pptx
Ā 
C-Programming File-handling-C.pptx
Ā 
File Handling in C
File Handling-Module V.pdf dSfcsvfsvcdfscfd
File Handling in C Programming for Beginners
637225560972186380.pdf
Ad

Recently uploaded (20)

PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Sports Quiz easy sports quiz sports quiz
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Complications of Minimal Access Surgery at WLH
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
BƀI Tįŗ¬P Bį»” TRỢ 4 KỸ NĂNG TIįŗ¾NG ANH 9 GLOBAL SUCCESS - Cįŗ¢ NĂM - BƁM SƁT FORM Đ...
PDF
RMMM.pdf make it easy to upload and study
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Pharma ospi slides which help in ospi learning
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
Cell Structure & Organelles in detailed.
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Ā 
Supply Chain Operations Speaking Notes -ICLT Program
Sports Quiz easy sports quiz sports quiz
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Complications of Minimal Access Surgery at WLH
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
O7-L3 Supply Chain Operations - ICLT Program
Microbial disease of the cardiovascular and lymphatic systems
102 student loan defaulters named and shamed – Is someone you know on the list?
BƀI Tįŗ¬P Bį»” TRỢ 4 KỸ NĂNG TIįŗ¾NG ANH 9 GLOBAL SUCCESS - Cįŗ¢ NĂM - BƁM SƁT FORM Đ...
RMMM.pdf make it easy to upload and study
Pharmacology of Heart Failure /Pharmacotherapy of CHF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Pharma ospi slides which help in ospi learning
TR - Agricultural Crops Production NC III.pdf
human mycosis Human fungal infections are called human mycosis..pptx
2.FourierTransform-ShortQuestionswithAnswers.pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
Cell Structure & Organelles in detailed.
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Ā 

File Handling in C Programming

  • 1. Lecture By Mr. Salunke R. B. on File Handling in C Programming To Assistant Professor & Head, Department of Computer Application, Dada Patil Mahavidyalaya, Karjat, Dist Ahmednagar, State Maharashtra
  • 2. Topic • File – Definition. Types of File, File Opening modes • File Functions – fopen(), fclose(), fgetc(), fputc(), fgets(), fputs(), fscanf(), fprintf(), getw(), putw(), fread(), fwrite(), fseek(),ftell() etc • File Management – Opening/Closing a File, Input/Output operations on , Error Handling During I/O Operations, Command Line Arguments • Random Access File
  • 3. File • Definition- ā€šA Collection of data or Information that are stored on computer permanently known as File‛ • Types of files – Text File Binary File • File Opening Modes – Read- ā€šr‛ , Write-ā€šw‛, Append-ā€ša‛ • r – Opens a file in read mode and sets pointer to the first character in the file. It returns null if file does not exist. • w – Opens a file in write mode. It returns null if file could not be opened. If file exists, data are overwritten. • a – Opens a file in append mode. It returns null if file couldn’t be opened.
  • 4. File Functions • fopen() – To open file • fclose() – To close file • fgetc() – To read character from file • fputc() – To write or add character to file • fgets() - To read string / line from file • fputs() - To write string / line to file • fscanf() – To scan data from file • fprintf() – To write data into file • getw() – To read Integer values from file • putw() – To write Integer values to file • fread() – To read character • fwrite() – To write character • fseek() – To read data • ftell() – go to End of file
  • 5. functions Description fopen () fopen () function creates a new file or opens an existing file. fclose () fclose () function closes an opened file. getw () getw () function reads an integer from file. putw () putw () functions writes an integer to file. fgetc () fgetc () function reads a character from file. fputc () fputc () functions write a character to file. gets () gets () function reads line from keyboard. puts () puts () function writes line to o/p screen. fgets () fgets () function reads string from a file, one line at a time. fputs () fputs () function writes string to a file. feof () feof () function finds end of file. fgetchar () fgetchar () function reads a character from keyboard. fprintf () fprintf () function writes formatted data to a file. fscanf () fscanf () function reads formatted data from a file. fputchar () fputchar () function writes a character onto the output screen from keyboard input. fseek () fseek () function moves file pointer position to given location. SEEK_SET SEEK_SET moves file pointer position to the beginning of the file. SEEK_CUR SEEK_CUR moves file pointer position to given location. SEEK_END SEEK_END moves file pointer position to the end of file.
  • 6. ftell () ftell () function gives current position of file pointer. rewind () rewind () function moves file pointer position to the beginning of the file. getc () getc () function reads character from file. getch () getch () function reads character from keyboard. getche () getche () function reads character from keyboard and echoes to o/p screen. getchar () getchar () function reads character from keyboard. putc () putc () function writes a character to file. putchar () putchar () function writes a character to screen. printf () printf () function writes formatted data to screen. sprinf () sprinf () function writes formatted output to string. scanf () scanf () function reads formatted data from keyboard. sscanf () sscanf () function Reads formatted input from a string. remove () remove () function deletes a file. fflush () fflush () function flushes a file.
  • 7. 1. EXAMPLE PROGRAM FOR FILE OPEN, FILE WRITE AND FILE CLOSE / * Open, write and close a file : */ # include <stdio.h> # include <string.h> void main( ) { FILE *fp ; char data[50]; // opening an existing file printf( "Opening the file test.c in write mode" ) ; fp = fopen("test.c", "w") ; if ( fp == NULL ) { printf( "Could not open file test.c" ) ; return 1; } printf( "n Enter some text from keyboard‛ ā€š to write in the file test.c" ) ; // getting input from user while ( strlen ( gets( data ) ) > 0 ) { // writing in the file fputs(data, fp) ; fputs("n", fp) ; } // closing the file printf("Closing the file test.c") ; fclose(fp) ; getch(); } Output Opening the file test.c in write mode Enter some text from keyboard to write in the file test.c Hai, How are you? Closing the file test.c
  • 8. File Management – • Opening/Closing a File • Input / Output operations on • Error Handling During I/O Operations • Command Line Arguments
  • 9. Open File • Declaration: FILE *fopen (const char *filename, const char *mode) • fopen() function is used to open a file to perform operations such as reading, writing etc. In a C program, we declare a file pointer and use fopen() as below. fopen() function creates a new file if the mentioned file name does not exist. • FILE *fp; fp=fopen (ā€šfilename‛, ā€›ā€˜mode‛); • Where, fp – file pointer to the data type ā€šFILE‛. filename – the actual file name with full path of the file. mode – refers to the operation that will be performed on the file. Example: r, w, a, r+, w+ and a+. Please refer below the description for these mode of operations.
  • 10. Close File • Declaration: int fclose(FILE *fp); • fclose() function closes the file that is being pointed by file pointer fp. In a C program, we close a file as below. fclose (fp);
  • 11. Read file - Line by Line • Declaration: char *fgets(char *string, int n, FILE *fp) • fgets function is used to read a file line by line. In a C program, we use fgets function as below. fgets (buffer, size, fp); • where, buffer – buffer to put the data in. size – size of the buffer fp – file pointer
  • 12. Write into file • Declaration: int fprintf(FILE *fp, const char *format, …);fprintf() function writes string into a file pointed by fp. In a C program, we write string into a file as below. fprintf (fp, ā€šsome data‛); or fprintf (fp, ā€štext %d‛, variable_name);
  • 13. Command Line Arguments in C • The arguments passed from command line are called command line arguments. These arguments are handled by main() function. • To support command line argument, you need to change the structure of main() function as given below. • int main(int argc, char *argv[] ) • Here, argc counts the number of arguments. It counts the file name as the first argument. • The argv[] contains the total number of arguments. The first argument is the file name always.
  • 14. Program #include <stdio.h> int main( int argc, char *argv[] ) { if( argc == 2 ) { printf("The argument supplied is %sn", argv[1]); } else if( argc > 2 ) { printf("Too many arguments supplied.n"); } else { printf("One argument expected.n"); } } You can run this program by 1. Go File Menu 2.Select Doss Shell Option 3. Type Program Name 4. and Type parameters
  • 15. Random Access File #include <stdio.h> int main () { FILE *fp; int c; fp = fopen("file.txt","w+"); fputs("This is study.com", fp); // we are using fseek to shift the file // pointer to the 7th position fseek( fp, 7, SEEK_SET ); //Now we overwrite C programming // in the 7th position fputs(" C Programming", fp); //now we print the current position of // the file pointer using ftell printf("The current position of the file pointer is: %ldn", ftell(fp)); //we take the file pointer to the // beginning of the file rewind(fp); //now we verify if rewind() worked // using ftell printf("The current position of the file pointer is: %ldn", ftell(fp));
  • 16. while(1) { c = fgetc(fp); if( feof(fp) ) { break; } printf("%c", c); } fclose(fp); return(0); } • Output The current position of the file pointer is: 21 The current position of the file pointer is: 0 This is C Programming