SlideShare une entreprise Scribd logo
1  sur  18
Can you C
File Handling
Rohan K.Gajre.
Drop me a line if I can do anything else for you.
rohangajre@gmail.com
why we need file handling?
To store the output of a program as well as
• Reusability: It helps in preserving the data or information generated after
running the program.
• Large storage capacity: Using files, you need not worry about the
problem of storing data in bulk.
• Saves time: Certain programs require a lot of input from the user. You can
easily access any part of the code with the help of certain commands.
• Portability: You can easily transfer the contents of a file from one
computer system to another without having to worry about the loss of data.
C Programming has some in build library
functions for same as following
• fopen():- Creating a new file or Opening an existing file in your system.
• fclose() :-Closing a file
• getc() :-Reading character from a line
• putc() :-Writing characters in a file
• fscanf():-Reading a set of data from a file
• fprintf():-Writing a set of data in a file
• getw():-Reading an integral value from a file
• putw():-Writing an integral value in a file
• fseek():-Setting a desired position in the file
• ftell():-Getting the current position in the file
• rewind():-Setting the position at the beginning point
• Simply we may say that if you want to save or read your C program output
then use file handling.
Steps for creating file handling
1 create file or open file(fopen())
2 select proper mode of file(r,w,a)
3 close file(fclose())
Common mode of file
• r To open a text file
• w To create or open a file in writing mode
• a To open a file in append mode
• r+ We use it to open a text file in both reading and writing mode
• w+ We use it to open a text file in both reading and writing mode
• a+ We use it to open a text file in both reading and writing mode
• rb We use it to open a binary file in reading mode
• wb We use it to open or create a binary file in writing mode
• ab We use it to open a binary file in append mode
• rb+ We use it to open a binary file in both reading and writing mode
• wb+ We use it to open a binary file in both reading and writing mode
• ab+ We use it to open a binary file in both reading and writing mode
1.Creating a file
• First, create your file pointer it as simple as creating a variable this
declaration is needed for communication between file and the program.
Syntax:
FILE *filepointername;
e.g.
FILE *fp;
2.Open a file
• Opening a file is performed using the fopen() defined in stdio.h headfile
Syntax:
Filepointer name=fopen(“filename.txt”,”mode”);
e.g. fp=fopen(“data.txt”,”w”);
3.Close a file
• The file must be closed after reading and writing.use fclose() function with
name of file pointer.
Synatx:
Fclose(filepointer);
e.g.
fclose(*fp);
• Here is a program in C that illustrates the use of file handling.
try it...
//Copy contents of one file to another
main()
{
FILE *wfp,*rfp;
char ch;
clrscr();
rfp = fopen("source","r");
wfp = fopen("target","w");
if(wfp==NULL || rfp==NULL)
{
printf("nUnable to open the file
");
getch();
exit();
}
while(!feof(rfp))
{
ch = fgetc(rfp);
fputc(ch,wfp);
}
printf("nCopied the file ");
fclose(wfp);
fclose(rfp);
getch();
return 0;
}
//WAP to accept 2 no and print result on file
void main() {
FILE *fp;
int num,i,prod;
clrscr();
fp = fopen("table.dat","w+");
printf("nEnter the integer number ");
scanf("%d",&num);
for(i=1;i<=10;i++) {
printf("n%d * %d = %d",num,i,num*i);
fprintf(fp,"%d %d %dn",num,i,num*i); }
rewind(fp);
getch(); clrscr();
printf("nThe table in the file is nnnn");
while(fscanf(fp,"%d %d %d",&num,&i,&prod)!=EOF)
printf("n%d * %d = %d",num,i,prod);
fclose(fp);
getch();
}
//Counting the number of charactrers, words and the lines in the file
main() {
FILE *rfp;
char ch;
int chars=0,words=0,lines=0;
clrscr();
rfp = fopen("source","r");
if(rfp==NULL) {
printf("nUnable to open the file ");
getch();
exit(); }
while(ch!=EOF) {
ch = fgetc(rfp);
if(ch!=' ' && ch!='n')
chars++;
else
words++;
if(ch=='n')
lines++; }
printf("nThe number of characters in the file are %d",chars);
printf("nThe number of words in the file are %d",words);
printf("nThe number of lines in the file are %d",lines);
fclose(rfp);
getch();
return 0;
}
//Reading the contents of the files
main() {
FILE *rfp;
char ch;
clrscr();
rfp = fopen("source","r");
if(rfp==NULL)
{
printf("nUnable to open the file ");
getch();
exit();
}
printf("nThe contents of the file are n");
while(!feof(rfp))
{
ch = fgetc(rfp);
printf("%c",ch);
}
fclose(rfp);
getch();
return 0; }
//Demo of fprintf () function
main()
{
FILE *wfp;
int num1=100,num2 = 200;
clrscr();
wfp = fopen("abc","w");
if(wfp==NULL)
{
printf("nUnable to open the file ");
getch();
}
printf("nThis is the statement on the screen ");
printf("n%d + %d = %d",num1,num2,num1+num2);
fprintf(wfp,"nThis is the statement in the screen");
fprintf(wfp,"n%d + %d = %d",num1,num2,num1+num2);
fclose(wfp);
getch();
return 0;
}
//Demo of fputc() function
main() {
FILE *wfp;
char ch;
clrscr();
wfp = fopen("text","w");
if(wfp==NULL)
{
printf("nUnable to open the file ");
getch(); }
printf("nEnter '$' to stop ");
while(1) {
scanf("%c",&ch);
if(ch=='$')
break;
fputc(ch,wfp);
}
fclose(wfp);
getch();
}
//Writing the table in file & reading from the file
main() {
FILE *fp;
int num,i,prod;
clrscr();
fp = fopen("table","w");
printf("nEnter the integer number ");
fscanf(stdin,"%d",&num);
for(i=1;i<=10;i++)
{
fprintf(stdout,"n%d * %d = %d",num,i,num*i);
fprintf(fp,"n%d * %d = %d",num,i,num*i);
}
getch();
fclose(fp);
clrscr();
fp = fopen("table","r");
printf("nThe contents of the file are n ");
while(fscanf(fp,"%d %d %d",&num,&i,&prod)!=EOF)
printf("n%d * %d = %d",num,i,prod);
getch(); }
//Record operations using the fprintf ()and fscanf () functions
struct student
{
char name[20];
int roll,age;
}S;
main() {
FILE *fp;
struct student S;
char ch;
fp = fopen("Stud.dat","a");
clrscr();
do
{
fprintf(stdout,"nEnter the details of the studemt ");
fscanf(stdin,"%s %d %d",S.name,&S.roll,&S.age);
fprintf(fp,"n%s %d %d",S.name,S.roll,S.age);
printf("nCont ..........");
fflush(stdin);
scanf("%c",&ch);
}while(ch=='y');
clrscr();
fclose(fp);
fp = fopen("Stud.dat","r");
printf("nthe details of the student are n");
while(!feof(fp))
{
fscanf(fp,"%s %d %d",S.name,&S.roll,&S.age);
printf("n%s t%d %dn",S.name,S.roll,S.age);
}
getch();
return 0;
}
//Concatenating two files in the third file
main()
{
char ch,ch1;
FILE *fp1,*fp2,*fp3;
clrscr();
fp1=fopen("file1","r");
fp2=fopen("file2","r");
fp3=fopen("file3","w");
if(fp1==NULL || fp2==NULL)
{
printf("nUnable to open the file ");
getch();
exit();
}
while(ch!=EOF)
{
ch=fgetc(fp1);
fputc(ch,fp3);
}
while(ch1!=EOF)
{
ch1=fgetc(fp2);
fputc(ch1,fp3);
}
fclose(fp1);
fclose(fp2);
fclose(fp3);
printf("n Task done ............. ");
getch();
return 0;
}
Thank You………

Contenu connexe

Tendances

C++ Tutorial
C++ TutorialC++ Tutorial
C++ Tutorialfreema48
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programmingAkshay Ithape
 
Introduction to programming with c,
Introduction to programming with c,Introduction to programming with c,
Introduction to programming with c,Hossain Md Shakhawat
 
Introduction of c language
Introduction of c languageIntroduction of c language
Introduction of c languagefarishah
 
Features of c language 1
Features of c language 1Features of c language 1
Features of c language 1srmohan06
 
A brief introduction to C Language
A brief introduction to C LanguageA brief introduction to C Language
A brief introduction to C LanguageMohamed Elsayed
 
Sachin kumar ppt on programming in c
Sachin kumar ppt on programming in cSachin kumar ppt on programming in c
Sachin kumar ppt on programming in cSachin Kumar
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programmingManoj Tyagi
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programmingMalikaJoya
 
The C++ Programming Language
The C++ Programming LanguageThe C++ Programming Language
The C++ Programming LanguageProf Ansari
 
introduction to c language
 introduction to c language introduction to c language
introduction to c languageRai University
 
Brief introduction to the c programming language
Brief introduction to the c programming languageBrief introduction to the c programming language
Brief introduction to the c programming languageKumar Gaurav
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C ProgrammingMOHAMAD NOH AHMAD
 
Computer programming - turbo c environment
Computer programming - turbo c environmentComputer programming - turbo c environment
Computer programming - turbo c environmentJohn Paul Espino
 
C & C++ Training Centre in Ambala! BATRA COMPUTER CENTRE
C & C++ Training Centre in Ambala! BATRA COMPUTER CENTREC & C++ Training Centre in Ambala! BATRA COMPUTER CENTRE
C & C++ Training Centre in Ambala! BATRA COMPUTER CENTREjatin batra
 
What is turbo c and how it works
What is turbo c and how it worksWhat is turbo c and how it works
What is turbo c and how it worksMark John Lado, MIT
 
Structure of C program
Structure of C programStructure of C program
Structure of C programPavan prasad
 
Unit 2 introduction to c programming
Unit 2   introduction to c programmingUnit 2   introduction to c programming
Unit 2 introduction to c programmingMithun DSouza
 

Tendances (20)

C++ Tutorial
C++ TutorialC++ Tutorial
C++ Tutorial
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
Introduction to programming with c,
Introduction to programming with c,Introduction to programming with c,
Introduction to programming with c,
 
Introduction of c language
Introduction of c languageIntroduction of c language
Introduction of c language
 
Features of c language 1
Features of c language 1Features of c language 1
Features of c language 1
 
A brief introduction to C Language
A brief introduction to C LanguageA brief introduction to C Language
A brief introduction to C Language
 
Sachin kumar ppt on programming in c
Sachin kumar ppt on programming in cSachin kumar ppt on programming in c
Sachin kumar ppt on programming in c
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programming
 
The C++ Programming Language
The C++ Programming LanguageThe C++ Programming Language
The C++ Programming Language
 
introduction to c language
 introduction to c language introduction to c language
introduction to c language
 
Brief introduction to the c programming language
Brief introduction to the c programming languageBrief introduction to the c programming language
Brief introduction to the c programming language
 
C Language
C LanguageC Language
C Language
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C Programming
 
Computer programming - turbo c environment
Computer programming - turbo c environmentComputer programming - turbo c environment
Computer programming - turbo c environment
 
C & C++ Training Centre in Ambala! BATRA COMPUTER CENTRE
C & C++ Training Centre in Ambala! BATRA COMPUTER CENTREC & C++ Training Centre in Ambala! BATRA COMPUTER CENTRE
C & C++ Training Centre in Ambala! BATRA COMPUTER CENTRE
 
OOP Poster Presentation
OOP Poster PresentationOOP Poster Presentation
OOP Poster Presentation
 
What is turbo c and how it works
What is turbo c and how it worksWhat is turbo c and how it works
What is turbo c and how it works
 
Structure of C program
Structure of C programStructure of C program
Structure of C program
 
Unit 2 introduction to c programming
Unit 2   introduction to c programmingUnit 2   introduction to c programming
Unit 2 introduction to c programming
 

Similaire à File handling With Solve Programs (20)

637225560972186380.pdf
637225560972186380.pdf637225560972186380.pdf
637225560972186380.pdf
 
File management
File managementFile management
File management
 
Unit5
Unit5Unit5
Unit5
 
Introduction to c part 4
Introduction to c  part  4Introduction to c  part  4
Introduction to c part 4
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in C
 
File handing in C
File handing in CFile handing in C
File handing in C
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
File handling in C
File handling in CFile handling in C
File handling in C
 
File operations in c
File operations in cFile operations in c
File operations in c
 
File mangement
File mangementFile mangement
File mangement
 
C-Programming Chapter 5 File-handling-C.ppt
C-Programming Chapter 5 File-handling-C.pptC-Programming Chapter 5 File-handling-C.ppt
C-Programming Chapter 5 File-handling-C.ppt
 
COM1407: File Processing
COM1407: File Processing COM1407: File Processing
COM1407: File Processing
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
 
file_c.pdf
file_c.pdffile_c.pdf
file_c.pdf
 
file management in c language
file management in c languagefile management in c language
file management in c language
 
File management
File managementFile management
File management
 
1file handling
1file handling1file handling
1file handling
 
File in c
File in cFile in c
File in c
 
File in C Programming
File in C ProgrammingFile in C Programming
File in C Programming
 

Dernier

microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 

Dernier (20)

microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 

File handling With Solve Programs

  • 1. Can you C File Handling Rohan K.Gajre. Drop me a line if I can do anything else for you. rohangajre@gmail.com
  • 2. why we need file handling? To store the output of a program as well as • Reusability: It helps in preserving the data or information generated after running the program. • Large storage capacity: Using files, you need not worry about the problem of storing data in bulk. • Saves time: Certain programs require a lot of input from the user. You can easily access any part of the code with the help of certain commands. • Portability: You can easily transfer the contents of a file from one computer system to another without having to worry about the loss of data. C Programming has some in build library functions for same as following • fopen():- Creating a new file or Opening an existing file in your system. • fclose() :-Closing a file • getc() :-Reading character from a line • putc() :-Writing characters in a file • fscanf():-Reading a set of data from a file
  • 3. • fprintf():-Writing a set of data in a file • getw():-Reading an integral value from a file • putw():-Writing an integral value in a file • fseek():-Setting a desired position in the file • ftell():-Getting the current position in the file • rewind():-Setting the position at the beginning point • Simply we may say that if you want to save or read your C program output then use file handling. Steps for creating file handling 1 create file or open file(fopen()) 2 select proper mode of file(r,w,a) 3 close file(fclose()) Common mode of file • r To open a text file • w To create or open a file in writing mode • a To open a file in append mode • r+ We use it to open a text file in both reading and writing mode • w+ We use it to open a text file in both reading and writing mode
  • 4. • a+ We use it to open a text file in both reading and writing mode • rb We use it to open a binary file in reading mode • wb We use it to open or create a binary file in writing mode • ab We use it to open a binary file in append mode • rb+ We use it to open a binary file in both reading and writing mode • wb+ We use it to open a binary file in both reading and writing mode • ab+ We use it to open a binary file in both reading and writing mode 1.Creating a file • First, create your file pointer it as simple as creating a variable this declaration is needed for communication between file and the program. Syntax: FILE *filepointername; e.g. FILE *fp; 2.Open a file • Opening a file is performed using the fopen() defined in stdio.h headfile Syntax: Filepointer name=fopen(“filename.txt”,”mode”); e.g. fp=fopen(“data.txt”,”w”);
  • 5. 3.Close a file • The file must be closed after reading and writing.use fclose() function with name of file pointer. Synatx: Fclose(filepointer); e.g. fclose(*fp); • Here is a program in C that illustrates the use of file handling. try it...
  • 6. //Copy contents of one file to another main() { FILE *wfp,*rfp; char ch; clrscr(); rfp = fopen("source","r"); wfp = fopen("target","w"); if(wfp==NULL || rfp==NULL) { printf("nUnable to open the file "); getch(); exit(); } while(!feof(rfp)) { ch = fgetc(rfp); fputc(ch,wfp); } printf("nCopied the file "); fclose(wfp); fclose(rfp); getch(); return 0; }
  • 7. //WAP to accept 2 no and print result on file void main() { FILE *fp; int num,i,prod; clrscr(); fp = fopen("table.dat","w+"); printf("nEnter the integer number "); scanf("%d",&num); for(i=1;i<=10;i++) { printf("n%d * %d = %d",num,i,num*i); fprintf(fp,"%d %d %dn",num,i,num*i); } rewind(fp); getch(); clrscr(); printf("nThe table in the file is nnnn"); while(fscanf(fp,"%d %d %d",&num,&i,&prod)!=EOF) printf("n%d * %d = %d",num,i,prod); fclose(fp); getch(); }
  • 8. //Counting the number of charactrers, words and the lines in the file main() { FILE *rfp; char ch; int chars=0,words=0,lines=0; clrscr(); rfp = fopen("source","r"); if(rfp==NULL) { printf("nUnable to open the file "); getch(); exit(); } while(ch!=EOF) { ch = fgetc(rfp); if(ch!=' ' && ch!='n') chars++;
  • 9. else words++; if(ch=='n') lines++; } printf("nThe number of characters in the file are %d",chars); printf("nThe number of words in the file are %d",words); printf("nThe number of lines in the file are %d",lines); fclose(rfp); getch(); return 0; }
  • 10. //Reading the contents of the files main() { FILE *rfp; char ch; clrscr(); rfp = fopen("source","r"); if(rfp==NULL) { printf("nUnable to open the file "); getch(); exit(); } printf("nThe contents of the file are n"); while(!feof(rfp)) { ch = fgetc(rfp); printf("%c",ch); } fclose(rfp); getch(); return 0; }
  • 11. //Demo of fprintf () function main() { FILE *wfp; int num1=100,num2 = 200; clrscr(); wfp = fopen("abc","w"); if(wfp==NULL) { printf("nUnable to open the file "); getch(); } printf("nThis is the statement on the screen "); printf("n%d + %d = %d",num1,num2,num1+num2); fprintf(wfp,"nThis is the statement in the screen"); fprintf(wfp,"n%d + %d = %d",num1,num2,num1+num2); fclose(wfp); getch(); return 0; }
  • 12. //Demo of fputc() function main() { FILE *wfp; char ch; clrscr(); wfp = fopen("text","w"); if(wfp==NULL) { printf("nUnable to open the file "); getch(); } printf("nEnter '$' to stop "); while(1) { scanf("%c",&ch); if(ch=='$') break; fputc(ch,wfp); } fclose(wfp); getch(); }
  • 13. //Writing the table in file & reading from the file main() { FILE *fp; int num,i,prod; clrscr(); fp = fopen("table","w"); printf("nEnter the integer number "); fscanf(stdin,"%d",&num); for(i=1;i<=10;i++) { fprintf(stdout,"n%d * %d = %d",num,i,num*i); fprintf(fp,"n%d * %d = %d",num,i,num*i); } getch(); fclose(fp); clrscr(); fp = fopen("table","r"); printf("nThe contents of the file are n "); while(fscanf(fp,"%d %d %d",&num,&i,&prod)!=EOF) printf("n%d * %d = %d",num,i,prod); getch(); }
  • 14. //Record operations using the fprintf ()and fscanf () functions struct student { char name[20]; int roll,age; }S; main() { FILE *fp; struct student S; char ch; fp = fopen("Stud.dat","a"); clrscr(); do { fprintf(stdout,"nEnter the details of the studemt "); fscanf(stdin,"%s %d %d",S.name,&S.roll,&S.age); fprintf(fp,"n%s %d %d",S.name,S.roll,S.age);
  • 15. printf("nCont .........."); fflush(stdin); scanf("%c",&ch); }while(ch=='y'); clrscr(); fclose(fp); fp = fopen("Stud.dat","r"); printf("nthe details of the student are n"); while(!feof(fp)) { fscanf(fp,"%s %d %d",S.name,&S.roll,&S.age); printf("n%s t%d %dn",S.name,S.roll,S.age); } getch(); return 0; }
  • 16. //Concatenating two files in the third file main() { char ch,ch1; FILE *fp1,*fp2,*fp3; clrscr(); fp1=fopen("file1","r"); fp2=fopen("file2","r"); fp3=fopen("file3","w"); if(fp1==NULL || fp2==NULL) { printf("nUnable to open the file "); getch(); exit(); }