







Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
This lecture is about File handling n C language. Codes about opening files, reading from files, end of file, writing to files, closing files, reading and writing files, appending a file are given in this lecture to explain the concept behind file handling. This concept exist for all languages like java and c++.
Typology: Slides
1 / 13
This page cannot be seen from the preview
Don't miss anything!








^ In C, each file is simply a sequential stream of bytes. Cimposes no structure on a file. ^ A file must first be opened properly before it can beaccessed for reading or writing. When a file is opened, astream is associated with the file. ^ Successfully opening a file returns a pointer to (i.e., theaddress of) a file structure, which contains a filedescriptor and a file control block.
^ The statement:
FILE *fptr1, *fptr2 ;
declares that
fptr
and
fptr
are pointer variables of type
FILE. They will be assigned the address of a filedescriptor, that is, an area of memory that will beassociated with an input or output stream. Whenever you are to read from or write to the file, youmust first open the file and assign the address of its filedescriptor (or structure) to the file pointer variable.
^ If the file was not able to be opened, then the valuereturned by the
fopen
routine is NULL.
^ For example, let's assume that the file
mydata
does not
exist. Then:
FILE *fptr1 ;fptr1 = fopen ( "mydata", "r") ;if (fptr1 == NULL){
printf ("File 'mydata' did not open.\n") ; }
^ In the following segment of C language code:
int a, b ;FILE *fptr1, *fptr2 ;fptr1 = fopen ( "mydata", "r" ) ;fscanf ( fptr1, "%d%d", &a, &b) ;
the^
fscanf
function would read values from the file "pointed" to by
fptr
and assign those values to
a^ and
b.
^ There are a number of ways to test for the end-of-filecondition. Another way is to use the value returned bythe
fscanf
function: int istatus ;istatus = fscanf (fptr1, "%d", &var) ;if ( istatus == EOF ){
printf ("End-of-file encountered.\n”) ; }
^ Likewise in a similar way, in the following segment of Clanguage code:
int a = 5, b = 20 ;FILE *fptr2 ;fptr2 = fopen ( "results", "w" ) ;fprintf ( fptr2, "%d %d\n", a, b ) ;
the fprintf functions would write the values stored in
a^ and
b^ to the file "pointed" to by
fptr
read_write.c
append.c