SlideShare a Scribd company logo
File Handling
Programming and Data Structure 1
What is a File?
 A file is a collection of related data stored as a unit
with a name to identify it.
 A file is a collection of related data that a computers
treats as a single unit.
 Computers stores files to secondary storage so that
the contents of files remain intact when a computer
shuts down.
 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.
• Discrete storage unit for data in the form of a
stream of bytes.
• Durable: stored in non-volatile memory.
• Starting end, sequence of bytes, and end of
stream (or end of file).
• Sequential access of data by a pointer
performing read / write / deletion / insertion.
• Meta-data (information about the file) before
the stream of actual data.
Programming and Data Structure 3
Steps in Processing a File
Create the stream via a pointer variable using
the FILE structure.
FILE *p;
Open the file, associating the stream name
with the file name.
Read or Write the data.
Close the file.
Spring 2012 Programming and Data Structure 5
40 65 87 90 24 67 89 90 0 0
Head Tail
File Pointer
Meta Data
• High-level programming languages support file operations
– Naming
– Opening
– Reading
– Writing
– Closing
General format for opening file
• fp
– contains all information about file
– Communication link between system and program
• Mode can be
– r open file for reading only
– w open file for writing only
– a open file for appending (adding) data
FILE *fp; /*variable fp is pointer to type FILE*/
fp = fopen(“filename”, “mode”);
/*opens file with name filename , assigns identifier to fp */
File handling in C
• In C we use FILE * to represent a pointer to a file.
• fopen is used to open a file. It returns the special value
NULL to indicate that it couldn't open the file.
Programming and Data Structure 8
FILE *fptr;
char filename[]= "file2.dat";
fptr= fopen (filename,"w");
if (fptr == NULL) {
printf (“ERROR IN FILE CREATION”);
/* DO SOMETHING */
}
Modes for opening files
• The second argument of fopen is the mode
in which we open the file. There are three
• "r" opens a file for reading
• "w" creates a file for writing - and writes over
all previous contents (deletes the file so be
careful!)
• "a" opens a file for appending - writing on the
end of the file
• “rb” read binary file (raw bytes)
• “wb” write binary file
Programming and Data Structure 9
The exit() function
• Sometimes error checking means we want
an "emergency exit" from a program. We
want it to stop dead.
• In main we can use "return" to stop.
• In functions we can use exit to do this.
• Exit is part of the stdlib.h library
Programming and Data Structure 10
exit(-1);
in a function is exactly the same as
return -1;
in the main routine
Usage of exit( )
FILE *fptr;
char filename[]= "file2.dat";
fptr= fopen (filename,"w");
if (fptr == NULL) {
printf (“ERROR IN FILE CREATION”);
/* Do something */
exit(-1);
}
Programming and Data Structure 11
Writing to a file using fprintf( )
• fprintf( ) works just like printf and sprintf
except that its first argument is a file pointer.
Programming and Data Structure 12
FILE *fptr;
fptr= fopen ("file.dat","w");
/* Check it's open */
fprintf (fptr,"Hello World!n");
Reading Data Using fscanf( )
FILE *fptr;
fptr= fopen (“input.dat”,“r”);
/* Check it's open */
if (fptr==NULL)
{
printf(“Error in opening file n”);
}
fscanf(fptr,“%d%d”,&x,&y);
Programming and Data Structure 13
•We also read data from a file using fscanf( ).
20 30
input.dat
x=20
y=30
Reading lines from a file using
fgets( )
We can read a string using fgets ( ).
Programming and Data Structure 14
FILE *fptr;
char line [1000];
/* Open file and check it is open */
while (fgets(line,1000,fptr) != NULL) {
printf ("Read line %sn",line);
}
fgets( ) takes 3 arguments, a string, a maximum
number of characters to read and a file pointer.
It returns NULL if there is an error (such as EOF).
Closing a file
• We can close a file simply using fclose( ) and
the file pointer.
Programming and Data Structure 15
FILE *fptr;
char filename[]= "myfile.dat";
fptr= fopen (filename,"w");
if (fptr == NULL) {
printf ("Cannot open file to write!n");
exit(-1);
}
fprintf (fptr,"Hello World of filing!n");
fclose (fptr);
Opening
Access
closing
Three special streams
• Three special file streams are defined in the
<stdio.h> header
• stdin reads input from the keyboard
• stdout send output to the screen
• stderr prints errors to an error device
(usually also the screen)
• What might this do?
Programming and Data Structure 16
fprintf (stdout,"Hello World!n");
An example program
Programming and Data Structure 17
#include <stdio.h>
main()
{
int i;
fprintf(stdout,"Give value of i n");
fscanf(stdin,"%d",&i);
fprintf(stdout,"Value of i=%d n",i);
fprintf(stderr,"No error: But an example to
show error message.n");
}
Give value of i
15
Value of i=15
No error: But an example to show
error message.
Display on
The screen
Input File & Output File redirection
• One may redirect the input and output files to
other files (other than stdin and stdout).
• Usage: Suppose the executable file is a.out
Programming and Data Structure 18
$ ./a.out <in.dat >out.dat
15
in.dat
Give value of i
Value of i=15
out.dat
No error: But an example to show error message.
Display
screen
Reading and Writing a character
• A character reading/writing is equivalent to
reading/writing a byte.
int getchar( );
int fgetc(FILE *fp);
int putchar(int c);
int fputc(int c, FILE *fp);
• Example:
char c;
c=getchar( );
putchar(c);
Programming and Data Structure 19
Example: use of getchar() and
putchar()
Programming and Data Structure 20
#include <stdio.h>
main()
{
int c;
printf("Type text and press return to see it again n");
printf("For exiting press <CTRL D> n");
while((c=getchar( ))!=EOF) putchar(c);
}
End of file
Command Line Arguments
• Command line arguments may be passed by
specifying them under main( ).
int main(int argc, char *argv[ ]);
Programming and Data Structure 21
Argument
Count Array of Strings
as command line
arguments including
the command itself.
Example: Reading command line arguments
Programming and Data Structure 22
#include <stdio.h>
#include <string.h>
int main(int argc,char *argv[])
{
FILE *ifp,*ofp;
int i,c;
char src_file[100],dst_file[100];
if(argc!=3){
printf("Usage: ./a.out <src_file> <dst_file> n");
exit(0);
}
else{
strcpy(src_file,argv[1]);
strcpy(dst_file,argv[2]);
}
Example: Contd.
Programming and Data Structure 23
if((ifp=fopen(src_file,"r"))==NULL)
{
printf("File does not exist.n");
exit(0);
}
if((ofp=fopen(dst_file,"w"))==NULL)
{
printf("File not created.n");
exit(0);
}
while((c=getc(ifp))!=EOF){
putc(c,ofp);
}
fclose(ifp);
fclose(ofp);
}
./a.out s.dat d.dat
argc=3
./a.out
s.dat
d.dat
argv
Getting numbers from strings
• Once we've got a string with a number in it
(either from a file or from the user typing)
we can use atoi or atof to convert it to a
number
• The functions are part of stdlib.h
Programming and Data Structure 24
char numberstring[]= "3.14";
int i;
double pi;
pi= atof (numberstring);
i= atoi ("12");
Both of these functions return 0 if they have a problem
Example: Averaging from Command
Line
Programming and Data Structure 25
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char *argv[])
{
float sum=0;
int i,num;
num=argc-1;
for(i=1;i<=num;i++)
sum+=atof(argv[i]);
printf("Average=%f n",sum/(float) num);
}
$ ./a.out 45 239 123
Average=135.666667

More Related Content

Similar to File_Handling in C.ppt

file.ppt
file.pptfile.ppt
file.ppt
DeveshDewangan5
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in C
Tushar B Kute
 
Files in c
Files in cFiles in c
Files in c
TanujaA3
 
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
sangeeta borde
 
File management
File managementFile management
File management
sumathiv9
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
Sandeepbhuma1
 
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
Muhammed Thanveer M
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
DHARUNESHBOOPATHY
 
Concept of file handling in c
Concept of file handling in cConcept of file handling in c
Concept of file handling in c
MugdhaSharma11
 
COM1407: File Processing
COM1407: File Processing COM1407: File Processing
COM1407: File Processing
Hemantha Kulathilake
 
Lecture 20 - File Handling
Lecture 20 - File HandlingLecture 20 - File Handling
Lecture 20 - File Handling
Md. Imran Hossain Showrov
 
Unit 8
Unit 8Unit 8
File management
File managementFile management
File management
AnishaThakkar2
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
yuvrajkeshri
 
File in c
File in cFile in c
File in c
Prabhu Govind
 
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
Ashim Lamichhane
 
File in C language
File in C languageFile in C language
File in C language
Manash Kumar Mondal
 
L8 file
L8 fileL8 file
File handling
File handlingFile handling
File handling
Ans Ali
 
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
AzanMehdi
 

Similar to File_Handling in C.ppt (20)

file.ppt
file.pptfile.ppt
file.ppt
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in C
 
Files in c
Files in cFiles in c
Files in c
 
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
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
 
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
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
Concept of file handling in c
Concept of file handling in cConcept of file handling in c
Concept of file handling in c
 
COM1407: File Processing
COM1407: File Processing COM1407: File Processing
COM1407: File Processing
 
Lecture 20 - File Handling
Lecture 20 - File HandlingLecture 20 - File Handling
Lecture 20 - File Handling
 
Unit 8
Unit 8Unit 8
Unit 8
 
File management
File managementFile management
File management
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
File in c
File in cFile in c
File in c
 
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
 
File in C language
File in C languageFile in C language
File in C language
 
L8 file
L8 fileL8 file
L8 file
 
File handling
File handlingFile handling
File handling
 
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
 

Recently uploaded

Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...
bijceesjournal
 
VARIABLE FREQUENCY DRIVE. VFDs are widely used in industrial applications for...
VARIABLE FREQUENCY DRIVE. VFDs are widely used in industrial applications for...VARIABLE FREQUENCY DRIVE. VFDs are widely used in industrial applications for...
VARIABLE FREQUENCY DRIVE. VFDs are widely used in industrial applications for...
PIMR BHOPAL
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
co23btech11018
 
Welding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdfWelding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdf
AjmalKhan50578
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
MDSABBIROJJAMANPAYEL
 
Engineering Standards Wiring methods.pdf
Engineering Standards Wiring methods.pdfEngineering Standards Wiring methods.pdf
Engineering Standards Wiring methods.pdf
edwin408357
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
Divyanshu
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
Yasser Mahgoub
 
SCALING OF MOS CIRCUITS m .pptx
SCALING OF MOS CIRCUITS m                 .pptxSCALING OF MOS CIRCUITS m                 .pptx
SCALING OF MOS CIRCUITS m .pptx
harshapolam10
 
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
IJECEIAES
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
Prakhyath Rai
 
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
upoux
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
21UME003TUSHARDEB
 
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
upoux
 
CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1
PKavitha10
 
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
Gino153088
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
kandramariana6
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
IJECEIAES
 
AI for Legal Research with applications, tools
AI for Legal Research with applications, toolsAI for Legal Research with applications, tools
AI for Legal Research with applications, tools
mahaffeycheryld
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 08 Doors and Windows.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 08 Doors and Windows.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 08 Doors and Windows.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 08 Doors and Windows.pdf
Yasser Mahgoub
 

Recently uploaded (20)

Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...
 
VARIABLE FREQUENCY DRIVE. VFDs are widely used in industrial applications for...
VARIABLE FREQUENCY DRIVE. VFDs are widely used in industrial applications for...VARIABLE FREQUENCY DRIVE. VFDs are widely used in industrial applications for...
VARIABLE FREQUENCY DRIVE. VFDs are widely used in industrial applications for...
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
 
Welding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdfWelding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdf
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
 
Engineering Standards Wiring methods.pdf
Engineering Standards Wiring methods.pdfEngineering Standards Wiring methods.pdf
Engineering Standards Wiring methods.pdf
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
 
SCALING OF MOS CIRCUITS m .pptx
SCALING OF MOS CIRCUITS m                 .pptxSCALING OF MOS CIRCUITS m                 .pptx
SCALING OF MOS CIRCUITS m .pptx
 
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
 
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
 
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
 
CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1
 
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
 
AI for Legal Research with applications, tools
AI for Legal Research with applications, toolsAI for Legal Research with applications, tools
AI for Legal Research with applications, tools
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 08 Doors and Windows.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 08 Doors and Windows.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 08 Doors and Windows.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 08 Doors and Windows.pdf
 

File_Handling in C.ppt

  • 1. File Handling Programming and Data Structure 1
  • 2. What is a File?  A file is a collection of related data stored as a unit with a name to identify it.  A file is a collection of related data that a computers treats as a single unit.  Computers stores files to secondary storage so that the contents of files remain intact when a computer shuts down.  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.
  • 3. • Discrete storage unit for data in the form of a stream of bytes. • Durable: stored in non-volatile memory. • Starting end, sequence of bytes, and end of stream (or end of file). • Sequential access of data by a pointer performing read / write / deletion / insertion. • Meta-data (information about the file) before the stream of actual data. Programming and Data Structure 3
  • 4. Steps in Processing a File Create the stream via a pointer variable using the FILE structure. FILE *p; Open the file, associating the stream name with the file name. Read or Write the data. Close the file.
  • 5. Spring 2012 Programming and Data Structure 5 40 65 87 90 24 67 89 90 0 0 Head Tail File Pointer Meta Data
  • 6. • High-level programming languages support file operations – Naming – Opening – Reading – Writing – Closing
  • 7. General format for opening file • fp – contains all information about file – Communication link between system and program • Mode can be – r open file for reading only – w open file for writing only – a open file for appending (adding) data FILE *fp; /*variable fp is pointer to type FILE*/ fp = fopen(“filename”, “mode”); /*opens file with name filename , assigns identifier to fp */
  • 8. File handling in C • In C we use FILE * to represent a pointer to a file. • fopen is used to open a file. It returns the special value NULL to indicate that it couldn't open the file. Programming and Data Structure 8 FILE *fptr; char filename[]= "file2.dat"; fptr= fopen (filename,"w"); if (fptr == NULL) { printf (“ERROR IN FILE CREATION”); /* DO SOMETHING */ }
  • 9. Modes for opening files • The second argument of fopen is the mode in which we open the file. There are three • "r" opens a file for reading • "w" creates a file for writing - and writes over all previous contents (deletes the file so be careful!) • "a" opens a file for appending - writing on the end of the file • “rb” read binary file (raw bytes) • “wb” write binary file Programming and Data Structure 9
  • 10. The exit() function • Sometimes error checking means we want an "emergency exit" from a program. We want it to stop dead. • In main we can use "return" to stop. • In functions we can use exit to do this. • Exit is part of the stdlib.h library Programming and Data Structure 10 exit(-1); in a function is exactly the same as return -1; in the main routine
  • 11. Usage of exit( ) FILE *fptr; char filename[]= "file2.dat"; fptr= fopen (filename,"w"); if (fptr == NULL) { printf (“ERROR IN FILE CREATION”); /* Do something */ exit(-1); } Programming and Data Structure 11
  • 12. Writing to a file using fprintf( ) • fprintf( ) works just like printf and sprintf except that its first argument is a file pointer. Programming and Data Structure 12 FILE *fptr; fptr= fopen ("file.dat","w"); /* Check it's open */ fprintf (fptr,"Hello World!n");
  • 13. Reading Data Using fscanf( ) FILE *fptr; fptr= fopen (“input.dat”,“r”); /* Check it's open */ if (fptr==NULL) { printf(“Error in opening file n”); } fscanf(fptr,“%d%d”,&x,&y); Programming and Data Structure 13 •We also read data from a file using fscanf( ). 20 30 input.dat x=20 y=30
  • 14. Reading lines from a file using fgets( ) We can read a string using fgets ( ). Programming and Data Structure 14 FILE *fptr; char line [1000]; /* Open file and check it is open */ while (fgets(line,1000,fptr) != NULL) { printf ("Read line %sn",line); } fgets( ) takes 3 arguments, a string, a maximum number of characters to read and a file pointer. It returns NULL if there is an error (such as EOF).
  • 15. Closing a file • We can close a file simply using fclose( ) and the file pointer. Programming and Data Structure 15 FILE *fptr; char filename[]= "myfile.dat"; fptr= fopen (filename,"w"); if (fptr == NULL) { printf ("Cannot open file to write!n"); exit(-1); } fprintf (fptr,"Hello World of filing!n"); fclose (fptr); Opening Access closing
  • 16. Three special streams • Three special file streams are defined in the <stdio.h> header • stdin reads input from the keyboard • stdout send output to the screen • stderr prints errors to an error device (usually also the screen) • What might this do? Programming and Data Structure 16 fprintf (stdout,"Hello World!n");
  • 17. An example program Programming and Data Structure 17 #include <stdio.h> main() { int i; fprintf(stdout,"Give value of i n"); fscanf(stdin,"%d",&i); fprintf(stdout,"Value of i=%d n",i); fprintf(stderr,"No error: But an example to show error message.n"); } Give value of i 15 Value of i=15 No error: But an example to show error message. Display on The screen
  • 18. Input File & Output File redirection • One may redirect the input and output files to other files (other than stdin and stdout). • Usage: Suppose the executable file is a.out Programming and Data Structure 18 $ ./a.out <in.dat >out.dat 15 in.dat Give value of i Value of i=15 out.dat No error: But an example to show error message. Display screen
  • 19. Reading and Writing a character • A character reading/writing is equivalent to reading/writing a byte. int getchar( ); int fgetc(FILE *fp); int putchar(int c); int fputc(int c, FILE *fp); • Example: char c; c=getchar( ); putchar(c); Programming and Data Structure 19
  • 20. Example: use of getchar() and putchar() Programming and Data Structure 20 #include <stdio.h> main() { int c; printf("Type text and press return to see it again n"); printf("For exiting press <CTRL D> n"); while((c=getchar( ))!=EOF) putchar(c); } End of file
  • 21. Command Line Arguments • Command line arguments may be passed by specifying them under main( ). int main(int argc, char *argv[ ]); Programming and Data Structure 21 Argument Count Array of Strings as command line arguments including the command itself.
  • 22. Example: Reading command line arguments Programming and Data Structure 22 #include <stdio.h> #include <string.h> int main(int argc,char *argv[]) { FILE *ifp,*ofp; int i,c; char src_file[100],dst_file[100]; if(argc!=3){ printf("Usage: ./a.out <src_file> <dst_file> n"); exit(0); } else{ strcpy(src_file,argv[1]); strcpy(dst_file,argv[2]); }
  • 23. Example: Contd. Programming and Data Structure 23 if((ifp=fopen(src_file,"r"))==NULL) { printf("File does not exist.n"); exit(0); } if((ofp=fopen(dst_file,"w"))==NULL) { printf("File not created.n"); exit(0); } while((c=getc(ifp))!=EOF){ putc(c,ofp); } fclose(ifp); fclose(ofp); } ./a.out s.dat d.dat argc=3 ./a.out s.dat d.dat argv
  • 24. Getting numbers from strings • Once we've got a string with a number in it (either from a file or from the user typing) we can use atoi or atof to convert it to a number • The functions are part of stdlib.h Programming and Data Structure 24 char numberstring[]= "3.14"; int i; double pi; pi= atof (numberstring); i= atoi ("12"); Both of these functions return 0 if they have a problem
  • 25. Example: Averaging from Command Line Programming and Data Structure 25 #include <stdio.h> #include <stdlib.h> int main(int argc,char *argv[]) { float sum=0; int i,num; num=argc-1; for(i=1;i<=num;i++) sum+=atof(argv[i]); printf("Average=%f n",sum/(float) num); } $ ./a.out 45 239 123 Average=135.666667