C Session10
C Session10
File Handling in C
l Opening a File
l Reading from a File
l argc and argv
l Formatted Disk I/O
File Handling in C
t FILE HANDLING That is where Files come in. A File is a set of records
FUNCTIONS that can be accessed by using certain library functions.
They allow us to store data permanently and from there,
t FORMATTED DISK
we can manipulate them as and when required.
INPUT AND OUTPUT
t OH! THOSE ERRORS A File is that which enables us to write the code and
save it for further use. It is then accessed by the compiler
and executed.
Library Functions
Comp-U-Learn
C Trim
The Library Functions that are most commonly used for File I/O are classified into High Level
File I/O and Low Level File I/O.
High Level File I/O: The High Level File I/O functions implement only the minimum functionality
to provide the basic API.
No buffering is done here, for instance a fwrite translates directly to a write. Here the code gets
reduced considerably and the interdependencies between functions are reduced.
Read and write functions are done a character at a time. The Input and Output is buffered and so
one need not bother about buffer size etc.
Low Level File I/O: The Standard I/O functions that are fundamentally dependent on the notion
of files are implemented in Low- Level I/O.
This is system dependent. Buffers and pointers to control the I/O process have to be provided here.
Opening a File
Before we access the contents of a file, we have to open it. C communicates with the files using a
new data type called file pointers. They are defined in stdio.h and are expressed as FILE*. A function
called fopen() returns the file pointer related to the file that was requested for. This pointer has to
be stored in a Pointer variable. This will hold the address of the file. If the file is not available, it
returns Null.
Why open a File? The purpose for doing it has to be specified. The choice is between Read, Write
or Append.
FILE *fp;
fp=fopen(“filename”,”mode”);
Comp-U-Learn
File Handling in C
fp is a pointer to the datatype FILE which becomes a communication link between the system and
the program, the next line opens the file that is named whatever we specify and assigns an
identifier to the FILE type pointer fp.
The mode in the second line specifies the purpose of opening the file.
r - Opens the file in read mode only on condition that the file is in existence.
w - Opens the file in the write mode only. If the file already exists, then it is overwritten. If it does
not exist then a new file is opened.
a - Opens the file in the append mode i.e. where data is added at the end of the file. If the file is non-
existent then a new file is created. Data is not over written.
r+ - Opens an existing file for reading and writing, provided the file exists.
w+ - Opens an empty file for reading and writing. If the file exists, the contents are destroyed.
a+ - The write operation results in appending of the data and existing data will not be overwritten.
Closing a File
After making use of the file, it has to be closed so as to flush all the outstanding information from
the buffers. This breaks all the links to the file. It also helps when many files on which operations
are complete and are opened unnecessarily.
When we open a file and perform a certain function and later want to open it in a different mode,
then it has to be closed and reopened.
fclose(fp);
This closes the file associated with the FILE pointer fp.
EXAMPLE
File *f1, *f2;
f1=fopen(“Input”,”w”);
f2=fopen(“Output”,”r”);
fclose(f1);
fclose(f2);
Comp-U-Learn
C Trim
This will open two files and close them after the purpose has been served. When the file is successfully
closed the same pointer can be used for another file.
Another interesting function is fseek(): Sometimes we may have the need to shift or skip certain
parts of a file and go to another part, while reading or writing into a file. When the file is opened,
the current position of that file is at the beginning of the file. When the current position is on the
last byte of the file, then it is the end of file.
rtn is assigned the value that is derived from fseek(file pointer, offset, from where);
The file -pointer will be one which points to a particular file, the offset is the number of bytes that
the current position is supposedly shifted and from where is the source from which it has to be
taken.
The rewind(): When reading or writing of a file is being done, there may be a need to return to the
beginning of the file. To return to the beginning of the file, the current position has to be shifted to
the beginning of the file.
This function takes a single argument, that is the file pointer pointing to the file that has to be
rewound.
rewind(file-pointer);
Once the function is called, the current position will appear at the beginning of the file. From
there on, the file can be manipulated using the necessary File functions.
Comp-U-Learn
File Handling in C
int fflush(File*stream)
int fclose(FILE*stream)
FILE *tmpfile(void)
void setbuf(FILE*stream,char*buf)
int fgetc(FILE*stream)
int getc(FILE*stream)
int ggetchar(void)
char gets(char*s)
Comp-U-Learn
C Trim
int putchar(int c )
To communicate with the operating system, two arguments are required which are argc and argv.
argc is the number of arguments on the command line including the command name itself. It
is an array of pointers to the strings.
argv is a pointer to an array of character strings that contain the arguments, i;e one argument for
each string. Its value is equal to the number of strings to which argv points.
The strings on the command line are passed on to main(). These strings are stored in the memory
and the address of the first string is stored in argv[0] and so on.
The number of strings given on the command line, is what is set to the argument argc.
Comp-U-Learn
File Handling in C
Here is how it is implemented. The main function here takes two arguments, argc and argv.
fscanf() considers the field separator to be a white space or a newline. Like in printf(), the data can
be formatted in a variety of ways, the fprintf() works in the same manner.
In the following program a file pointer fp is declared. The name age and social security number of
the citizen is accepted from the user and written into the file.
1. #include <stdio.h>
2. main()
3. {
4. FILE *fp;
5. char sub =’Y’;
6. char name[20];
7. int age;
8. float ssn;
9. fp = fopen (“subject.txt”, “w”);
10. if(fp==NULL)
11. {
12. puts(“Can not open file”);
Comp-U-Learn
C Trim
13. exit();
14. }
15. while(sub ==’Y’)
16. {
17. printf(“\n Enter the subject’s name\n”);
18. scanf(“%s”,name);
19. printf(“\n Enter the subject’s age”);
20. scanf(“%d”, age);
21. printf(“\n Enter the subject’s social security number\n”);
22. scanf(“%f”,ssn);
23. fprintf(fp, “%s,%d,%f”, name, &age, &ssn);
24. fflush(stdin);
25. sub = getche();
26. }
27. fclose(fp);
28. }
In the above program, line 4 shows that a file pointer fp is declared. In line 9, a file called subject
.txt is opened in the write mode using fopen(). The w accompanying it shows that it is opened in
the write mode. The program then tests whether the file can be opened. If it can not be opened, an
appropriate message is displayed. It then proceeds to accept the input from the users in the form of
the citizens name, age and social security number. You will notice that in line 23, the use of
fprintf() prints the result in the file. Finally the fclose() is used to close the file.
O H! T HOSE ERRORS
While using Files, if the fopen() fails, or for any other reason if there is a failure, then the pointer
is not set up correctly. In this case do not be surprised if you are faced with some unrecognizable
output.
To prevent unexpected results, your program should always check that the file-handling functions
have done their job successfully. You can do this by checking the return value.
The following methods can be used to check whether the fopen() has worked successfully.
FILE *fp;
fp=fopen(“test-file.dat”,”rb”);
if (fp==NULL)
{
printf(“\nError opening data file\n”);
Comp-U-Learn
File Handling in C
exit();
}
When fopen() is successful, then it returns a value of a pointer. This will be stored in fp. If it is
unsuccessful, then the value returned is NULL.
The following method can be used to check after writing into a file.
Sometimes a program might appear to finish normally, but after that none of the expected data
will be written to the file.
Fwrite() returns the number of items that have been successfully written.
This example shows how fclose() returns the number of items written.
FILE *fp;
int ab;
char ch;
ab= fwrite(&ch,1,1,fp);
if (ab == 0)
{
printf(“\nError writing to file\n”);
exit();
}
To check the successful reading of a file, the following methods can be used.
fread() returns a value pertaining to the number of items that are read. It may return Zero if no
items were read, or if it reaches the end of file.
This code shows how the fread() function and an feof() work.
FILE *fp;
int ab;
char ch;
ab= fread(&ch,1,1,fp);
if (ab==0)
{
if (feof(fp)==0)
printf(“\nError reading from file\n”);
else
Comp-U-Learn
C Trim
The following method helps to terminate a program, where errors have occurred in File Input/
Output.
Exit()
If(argc!=3)
{
printf(“Invalid arguments \n”);
exit();
}
The functions that are involved in File handling may seem a bit confusing at first, but once you
figure out their logical reason, they simply make sense.
http://www.lysator.liu.se/c/rat/title.html
T HE Z ERO H OUR
Q: What are the two broad category functions of I/O files?
Q: What is the link between the program and the operating system?
Ans: FILE is link between the program and the operating system which is specified in the stdio.h
header file.
Q: What is the standard function from the library that is used to open a file?
Ans: fopen().
Comp-U-Learn
File Handling in C
Q: What is the standard function from the library that is used to open a file?
Ans: fclose().
Q: What is the standard function from the library that is used to check error?
Ans: ferror().
Q: What are the two arguments used for effective file handling?
Ans: argc and argv are the two arguments used for effective file handling.
T HE S ESSION G UIDE
The Session Guide helps you time your session with the help of the slides provided. Beneath each
image of the slides, the time to be spent on each slide while it is being displayed is given. The slide
will thus, guide you through the contents of the session with ease.
Programming Using C
File Handling in C
Slide 1 Comp-U-Learn
Display Time
This is the introductory slide and should take 5 minutes to ease the students. You can talk about
the File handling in C.
Comp-U-Learn
C Trim
Road Map
Slide 2
Comp-U-Learn
Display Time
When you display this slide, all the major topics that would be covered in this session should be
discussed. You can spend about 10 minutes on this slide.
The functions of the disk I/O or file I/O divided into two categories
Slide 3
Comp-U-Learn
Display Time
Here, you will discuss the Disk I/O or File I/O. You need to spend 20 minutes on this slide.
Comp-U-Learn
File Handling in C
High level
Text Binary
Display Time
Opening a File
Format:
FILE *fp;
fp=fopen(“prog1.c”,”r”);
(fp is the pointer variable,r for read only mode).
Slide 5
Comp-U-Learn
Display Time
This slide discusses about opening of a file. You can spend 5 minutes to explain the process of
opening of a file.
Comp-U-Learn
C Trim
Reading a file
Format
ch=getc(fp);
(ch the variable,fp file pointer).
Display Time
This slide can be helpful in reading a file. To explain this process, you can take 6 minutes.
Closing a file
General format:
fclose(fp);
(fp is the file pointer).
Slide 7
Comp-U-Learn
Display Time
You will discuss the closing of a file when this slide is displayed. The display time for this slide is 4
minutes.
Comp-U-Learn
File Handling in C
Display Time
While this slide is on display, you will discuss the various types of file opening modes. Time spent
can be 10 minutes.
Trouble shooting
# i nc lu d e< s td i o. h>
m ain ( )
{
F ILE *f p ;
f p= f ope n (“ p ro g 1 .c” , “ r ”) ;
i f(f p == NU L L)
{
p rin t f( “ Fi l e no t A c ce ss i bl e ”) ;
e xit ( );
}
Slide 9
Comp-U-Learn
Display Time
You discuss about the trouble shooting. You can spend approximately 10 minutes on this slide.
Comp-U-Learn
C Trim
#include<stdio.h>
main()
{
FILE f;
char data;
printf(“Enter few characters\n”);
f=fopen(“write”,”w”);
while((data=getchar())!=EOF)
putc(data,f);
Slide 10 fclose(f);
} Comp-U-Learn
Display Time
This slide helps you in discussing the process for writing into a file. Spend 10 minutes when you
display this slide.
String input
⇒fputs() is used to input string in a file.
⇒Fgets() to accept strings.
General format
fputs(string,ptrvar);
Example # i nc l ud e <s t d i o . h >
m a in ( )
{
F IL E * p t r ;
c ha r s t r [ 5 0] ;
p t r = f o p e n ( “s tr i n g . TX T ” , “ w” ) ;
i f( p t r = = N U L L )
{
p r i n t f ( “ fi l e n o t ac c e s s i b l e ”) ;
exit();
}
p r i n t f ( “ p en d o w n a f e w l i n e s ”) ;
w hi l e ( s t r l e n (g e t s ( s t r )) > 0 )
{
f pu t s( s t r , p tr ) ;
}
Slide 11 }
f cl o se ( pt r ) ;
Comp-U-Learn
Display Time
While displaying this slide, you will talk about the strng input and you can spend nearly 12
minutes on this slide.
Comp-U-Learn
File Handling in C
General format
main(argc,argv)
int argc;
char *argv[];
Slide 12 Comp-U-Learn
Display Time
When you show this slide, you will discuss the ARGV and ARGC. You can spend 10 minutes on
this slide.
General format:
fprintf(ptr,” %s%d..”,var1,var2..);
Example:
printf(“enter name, number and salary”);
scanf(“%s%d%f”,name, &no,&sal);
fprintf(ptr, “%s%d%f”, name, &no,&sal);
Slide 13
Comp-U-Learn
Display Time
Discuss about the Formatted disk I/O when this slide is on display. The time spent on this slide can
be 10 minutes.
Comp-U-Learn
C Trim
Slide 14
Comp-U-Learn
Display Time
You discuss the function ferror when this slide is displayed. Spend just 2 minutes.
Display Time
The Going over it slide finishes the entire session and explains all that has been covered in this
session briefly. You need to discuss this slide for about 6 minutes.
Comp-U-Learn