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

unit4_adv_c

This document provides an overview of file handling in C programming, detailing the importance of file operations for managing large volumes of data. It covers file access modes, input/output operations, and error handling during file operations, including functions like fopen, fclose, getc, putc, fprintf, and fscanf. Additionally, it discusses error detection methods using feof and ferror to ensure proper file management.

Uploaded by

panchaljaydip791
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

unit4_adv_c

This document provides an overview of file handling in C programming, detailing the importance of file operations for managing large volumes of data. It covers file access modes, input/output operations, and error handling during file operations, including functions like fopen, fclose, getc, putc, fprintf, and fscanf. Additionally, it discusses error detection methods using feof and ferror to ensure proper file management.

Uploaded by

panchaljaydip791
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

UNIT 4 BCA SEM -2 Advance C.

St.Stephen Institute of Business Management and Technology, Anand

UNIT 4 USAGE OF FILE HANDLING

 Introduction to File Handling


 File Access Modes
 Input Output Operations on files
 Error Handling during I/O operations

Introduction to File Handling:

Function scanf and printf are used for read and write data. These are console
oriented I/O functions, which always use the terminal(keyboard and screen) as the
target place. This work fine as long as the data is small. Many real life problems
involve large volume of data and in such situations; the console oriented I/O
operations pose two major problems.

1. It becomes cumbersome and time consuming to handle large volume of data


through terminals.
2. The entire data is lost when either the program is terminated or the
computer is turned off.

It is therefore to have a more flexible approach where data can be stored on the
disks and read whenever necessary, without destroying the data. The method employs the
concept of files to store the data. A file is a place on the disk where a group of related data
is stored. Like most other languages, c supports a number of functions that have the ability
to perform basic file operations, which include

 Naming a file,
 Opening a file,
 Reading a data from a file,
 Writing a data to a file and
 Closing a file.

There are two distinct ways to perform the file operation in c. The first one is known as the
low level I/O and uses UNIX system calls. The second method is referred to as the high-level
I/O operation and uses function in C's standard I/O library. There are listed in table.

Function Name Operation


fopen() Creates a new file for use.
Opens an existing file for use.
fclose() Close a file which has been opened for use.
getc() Reads a character from a file.
putc() Writes a character to a file.
fprintf() Writes a set of data values to a file.
fscanf() Reades a set of data values from a file.
getw() Reads an integer from file.
putw() Writes an integer from a file.

Prepared By: Patel Ruchi Page 1


UNIT 4 BCA SEM -2 Advance C.

There are many other functions. Not all of them are supported by all compilers.

Defining and Opening a File:

If we want to store data in a file in the secondary memory, we must specify certain things
about the file to the operating system. They include:

1. File Name.
2. Data Structure
3. Purpose

Filename is a string of characters that make up a valid filename for the operating
system. It may contain two parts, a primary name and an optional period it the
extension.
Examples:

Input.data
Store
Prog.c
Student.c
Text.out
Data structure of a file if defined as FILE in the library of standard I/O function
definitions. Therefore, all files should be declared as type FILE before they are used.
FILE is a defined data type. When we open a file, we must specify what we want to
do with the file. for example, we may write data to the file or read the already
existing data. Following is the general format for declaring and opening a file:

FILE *fp;
fp = fopen("filename","mode");
The first statement declared the variable fp "pointer to the data type FILE" is a
defined data type. File is structured that is defined in I/O library. The second
statement opens the file named filename and assigns an identifier to the FILE type
pointer fp. This pointer which contains all the information absolute the file is
subsequently used as a communication link between the system and the program.

The second statement also specifies the purpose of opening this file. The mode does
this job. Mode can be one of the following.
r Open the file for reading only.
w Open the file for writing only.
a Open the file for appending(or editing) data to it.

Both the filename and mode are specified as strings. They should be enclosed in
double quotation marks. When trying to open a file, one of the following things may
happen:
1. When the mode is 'writing' , a file with the specified name is created if the
file does not exist. The content is detect, if the file already exists.

Prepared By: Patel Ruchi Page 2


UNIT 4 BCA SEM -2 Advance C.

2. When the purpose is 'appending' , the file is opened with the current
contents safe. A file with the specified name is created if the file does not
exist.
3. If the purpose is 'reading', and if it exists, then the file is opened with the
current contents safe otherwise an error occurs.

Consider the following statements:

FILE *p1,*p2;

p1 = fopen("data","r");

p2=fopen("results","w");

the file data is opened for reading and results is opened for writing. In case, the result file
already exists, its content is detected and file is opened as a new file. If data file does not
exist, an error will occur.

Many recent compilers include additional modes of operation. They include:

r+ the existing a file is opened to the beginning for reading and writing.

w+ same as w except both for reading and writing.

a+ same as a except both for reading and writing.

Closing File:

A file must be closed as soon as all operations on it have been completed. This ensures that
all outstanding information associated with the file is flushed out from the buffers and all
links to the file are broken. It also prevents any accidental misuse of the file. In case, there
is a limit to the number of files that can be kept open simultaneously, closing of unwanted
files might help open the required files. Another instance where we have to close a file is
when we want to reopen the same file in a different mode. The I/O library supports a
function to do this for us. It takes the following form:

fclose(file_pointer);

This would close the file associated with the FILE pointer file_pointer.Looks at the following
segment of a program.

-------

-------

FILE *p1,*p2;

p1=fopen("INPUT","w");

p2=fopen("OUTPUT","r");

Prepared By: Patel Ruchi Page 3


UNIT 4 BCA SEM -2 Advance C.

-------

-------

fclose(p1);

fclose(p2);

--------

This program opens two files and closes them after all operations on them are completed.
Once a file is closed, Its file pointer can be reused for another file. As matter of fact files are
closed automatically whenever a program terminates.

INPUT OUTPUT OPERATIONS ON FILES:

Once a file is opened, reading out of writing to it is accomplished using the statement I/O
routines.

The getc and putc functions

The simplest file I/O functions are getc and putc. These are analogous to getchar and
putchar functions and handle one character at a time. Assume that a file is opened with
mode w and file pointer fp1. Then, the statement

putc(c,fp1);

writes the character combined in the character variable c to the file associated with FILE
pointer fp1.Similarly,getc is used to read a character from a file that has been opened in
read mode. For example, the statement

c=getc(fp2);

would read a character from the file whose file pointer is fp2.

The file pointer moves by one character position for every operation of getc and putc. The
getc will return an end-of-file maker EOF, when end of the file has been reached. Therefore,
the reading should be terminated when EOF is encountered.

The getw and putw function:

The getw and putw are integer-oriented functions. They are similar to the getc and putc
function and are used to read and write integer values. These functions would be useful
when we deal with only integer data. The general forms of getw and putw are:

putw(integer,fp);

getw(fp);

Prepared By: Patel Ruchi Page 4


UNIT 4 BCA SEM -2 Advance C.

The fprintf and fscanf functions:

Most compilers support two other functions, namely fprintf and fscanf, that can handle a
group of mixed data simultaneously.

The function fprintf and fscanf perform I/O operations that are identical to the familiar
printf and scanf functions, expect of course that they work on files. The first argument of
these functions is a file pointer which specifies the file to be used. The general form of
fprintf is

fprintf(fp,"control string",list);

where fp is a file pointer associated with a file that has been opened for writing. The control
string contains output specifications for the items in the list. The list may include variables,
constants and string.

Example:

fprintf (f1,"%s%d%f",name,age,7.5);

here, name is an array variable of type char and age is an int variable.

The general format of fscanf is

fprintf (fp, "control string" ,list);

This statement would cause the reading of the items inthe list from the file specified by fp,
according to the specifications contained in the control string.

Example:

fscanf (f2,"%s %d", item ,&quantity);

like scanf, fscanf also returns the number of items that are successfully read. When the end
of file is reached, it returns the value EOF.

ERROR HANDLING DURING I/O OPERATIONS:

It is possible that an error may occur during I/O operations on file. Typical error situations
include:

1. Trying to read beyond the en-of-file mark.


2. Devise overflow.
3. Trying to use a file that has not been opened.
4. Trying to perform an operation on a file, when the file is opened for another type of
operation.
5. Opening a file with an invalid filename.
6. Attempting to write to a write-protected file.

If we fail to check such read and write errors, a program may behave abnormally when an
error occurs. An unchecked error may result in a premature termination of the program or

Prepared By: Patel Ruchi Page 5


UNIT 4 BCA SEM -2 Advance C.

incorrect output. Fortunately, we have two status-inquiry library functions; feof and ferror
that can help us detect I/O errors in the files.

The feof function can be used to test for an end of file condition. It takes a FILE pointer as its
only argument and returns a nonzero integer value if all of the data from the specified file
has been read, and retunes zero otherwise. If fp is a pointer to file that has just been
opened for reading, then the statement

if(feof(fp))

printf("End of data.\n");

would display the message "End of data" .On reaching the end of file condition.

The ferror function reports the status of the file indicated. It also takes a FILE pointer as its
argument and returns a nonzero integer if an error has been detected up to that point,
during processing. It returns zero otherwise. The statement

if( ferror(fp) !=0)

printf("An error has occurred \n");

would print the error message, if the reading is not successful.

We known that whenever a file is opened using fopen function, a file pointer is returned. If
the file cannot be opened for some reason, then the function returns a NULL pointer. This
facility can be used to test whether a file has been opened or not.

Examples:

if(fp== NULL)

printf("File could not be opened.\n");

Prepared By: Patel Ruchi Page 6

You might also like