0% found this document useful (0 votes)
40 views

C Session10

The document discusses file handling in C. It describes opening, reading from, and closing files using functions like fopen(), fread(), fwrite(), and fclose(). It explains that files allow permanent storage of data that can be accessed and manipulated by programs. Different file access modes are also outlined, including read, write and append modes.

Uploaded by

Yogi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

C Session10

The document discusses file handling in C. It describes opening, reading from, and closing files using functions like fopen(), fread(), fwrite(), and fclose(). It explains that files allow permanent storage of data that can be accessed and manipulated by programs. Different file access modes are also outlined, including read, write and append modes.

Uploaded by

Yogi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Session 10

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

I NTRODUCTION TO F ILE H ANDLING


When a program is written, it is definitely expected to
work successfully. When it does; the joy is
incomparable. A major reason for the need to use files
is that, when the output is generated from the source
code, it has to be stored in a secondary device, otherwise
it remains in the buffer, and is lost permanently on
t INTRODUCTION TO turning off the system.
F ILE H ANDLING
We do go through a lot of read/write functions, which
t MEET THE FILE are in auxiliary storage, while writing a program. If
HANDLING CREW this data is not saved in the permanent memory of the
t OPENING, READING computer, then all the hard work and success becomes
AND CLOSING A FILE
a thing of the past.

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.

C treats File Input/Output in the same manner as it


treats Input/Output with a terminal.

M EET THE F ILE H ANDLING C REW


After discussing the need for Files, let us now understand
as to how well we can manipulate these Files for better
program performance. C treats a File as a stream of
characters. Specific functions however work for single
character or for multiple characters respectively.

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.

O PENING , R EADING AND C LOSING A F ILE


This is where the action begins. Now that we know what Functions help us to interact with the
files, let us now begin by Opening a File.

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.

To declare and open a file:

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.

The following are the different modes that can be specified.

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.

The fseek() is used to reposition the current position.

The syntax for the fseek would have to be :

rtn = fseek (file-pointer,offset,from-where);

This function returns an integer if it is successful and 1 if it is unsuccessful.

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.

F ILE H ANDLING F UNCTIONS


Listed below are a number of functions that make file handling a simple affair.

Comp-U-Learn
File Handling in C

Return Type Functions and their arguments

FILE *fopen(const char *filename, const char *mode)

FILE *freopen(const char *filename, const char *mode,


FilE * stream)

int fflush(File*stream)

int fclose(FILE*stream)

int remove(const char *filename)

int rename(const char *oldname, const char *newname)

FILE *tmpfile(void)

char *tmpnam(char s[L_tmpnam])

int setvbuf(FILE *stream, char *buf, int mode,size_tsize)

void setbuf(FILE*stream,char*buf)

int fprintf(FILE*stream,const char* format,..)

int sprintf(char*s,const char*format,…)

int vprintf(const char *format,va_list arg)

int vprintf(char*s,const char*format,va_list arg)

int fscanf(FILE*stream,const char*format,…)

int sscanf(const char*format,…)

int sscanf(char *s, const char *format, ...)

int fgetc(FILE*stream)

char fgets(chars,int n,FILE*stream)

int fputc(int c, FILE*stream)

int fputs(const char*s,FILE*stream)

int getc(FILE*stream)

int ggetchar(void)

char gets(char*s)

Comp-U-Learn
C Trim

Return Type Functions and their arguments

int putc(int c , FILE *stream)

int putchar(int c )

int puts(const char *s)

int ungetc(int c, FILE *stream)

size_t fread(void*ptr,size_tsize,size_t nobj,FILE*stream)

size_t fwrite(const void *ptr, size_t size, size_t nobj,


FILE *stream)

int fseek(FILE*stream,long offset, int origin)

long ftell(FILE *stream)

void rewind(FILE *stream)

int fgetpos(FILE *stream, fpos_t *ptr)

int fsetpos(FILE stream,const fpos_t *ptr)

void clearerr(FILE *stream)

int feof(FILE *stream)

int ferror(FILE *stream)

void perror(const char *s)

Argc , argv – Arguments to Main().

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. It’s 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.

1. int main (int argc, char **argv)


2. {
3. int i;
4. while (—argc > 0)
5. printf(“\n%s%s”, *++argv, (argc > 1) ? “ “ : “”);
6. printf(“\n”);
7. return 0;
8. }
In the above program, the main function takes two arguments, the argc is an integer type and the
argv is a character type. When the arguments are greater than zero, the respective values are
printed.

F ORMATTED D ISK I NPUT AND O UTPUT


Files containing a fixed format can be read in C using fscanf() and fprintf(). Here the pointer to the
file has to be specified. This is the first parameter of both functions. The other parameters however
are much the same as printf() and scanf().

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.

If it is the later, then feof() helps to find 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

printf(“\nEnd of file reached\n”);


}

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.

U RLS FOR F ILE HANDLING IN C


Extended Reference

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?

Ans: The two broad category functions of I/O files are:

Low level file I/O

High level file I/O

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

• Introduction to File • Writing into a File


Handling • ArgC and ArgV
• Opening a File • String Input
• Reading from a File • Formatted Disk I/O
• Closing a File • Error Display
• Trouble Shooting Function
• File Opening Modes • Do’s and Don’ts

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.

An Introduction to File handling

The functions of the disk I/O or file I/O divided into two categories

Disk I/O functions

High level Low level

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 file I/O

High level I/O divided into the following categories

High level

Text Binary

Formatted Unformatted Formatted Unformatted


Slide 4
Comp-U-Learn

Display Time

Continuation of the previous slide.

Opening a File

⇒#include <stdio.> statement must be included.


⇒Name of the file has to be specified.
⇒Mode should be specified.
⇒Pointer variable should be used.

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

⇒Contents can be read with getc() library function.


⇒This function reads character by character.
⇒The collection is then returned by a variable.
⇒End of the file can be known by special character EOF.

Format

ch=getc(fp);
(ch the variable,fp file pointer).

Note: File once opened referred through file pointer.


Slide 6
Comp-U-Learn

Display Time

This slide can be helpful in reading a file. To explain this process, you can take 6 minutes.

Closing a file

⇒It is mandatory to close the file at end.


⇒File closed by library function fclose().
⇒Once closed cannot be accessible by getc().

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

File Opening modes

S.no. Mode Operations possible

1. “r” Read only.

2. “w” Writing to file

3. “a” Appending new contents

4. “r+” Reading and modifying existing contents,


writing new contents.

5. “w+” Writing new contents and modifying existing


contents.

6. “a”+” Reading existing contents and appending


new contents at the end of the file.
Slide 8
Comp-U-Learn

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

⇒Check should be made before opening a program.

⇒Ensure that message is displayed about error if encountered.


Example

# 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

Writing into a file

⇒Putc() is used to input the characters.


⇒For recursive writing loop should be used.
Example:

#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

Argv and Argc

⇒They are arguments for main function.


⇒Used as a shortcut for effective file handling.
⇒Not required to compile source code if these arguments used.

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.

Formatted disk I/O

⇒With I/O data can be written into file.


⇒It is necessary to specify pointer variable as an argument.

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

The function ferror

⇒It is a standard library function.

⇒Returns zero if no error.

⇒Returns non-zero if error.

Slide 14
Comp-U-Learn

Display Time

You discuss the function ferror when this slide is displayed. Spend just 2 minutes.

Going Over it Again

• Disk I/O functions are divided into high level and


low level
• File is opened by fopen() library function
• getc() library function is used to read the contents
of a file
• File is closed by library function fclose()
• putc() is used to input the characters
• ArgV and ArgC are the two arguments used in
main.
Slide 15 • The function ferror() is used check to the errors
Comp-U-Learn

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

You might also like