PART 10
PART 10
Introduction:
Until now, we are handling data by using functions such as scanf() and printf(). These are console
oriented I/O functions which always use screen as a target place. However, the console oriented input
output management results in two major problems.
o It is time consuming to handle large volumes of data through terminals.
o The entire data is lost when either program is terminated (or) the computer is turned off.
To overcome the above problems the data can be stored on the disk and can be used whenever
necessary. This method employees the concept of files to store data.
File:-
File is a set of records that can be accessed through the set of library functions.
Streams:-
Stream means reading and writing of data.
The streams are designed to allow the user to access the files efficiently.
A stream is a file or physical device like keyboard, printer and monitor.
The FILE object uses these devices.
File types:-
There are two types of files, namely
1. Sequential file
2. Random Access file
Sequential File:-
In this type records are kept sequentially.
If we want to read the last record of the file , then we need to read all the records before that record.
Random Access File:-
In this type data can be read and modified randomly.
In this type , if we want to read the last records of the file, we can read it directly.
It takes less time as compared to sequential file.
File Management:
A file is a place on the disk where a group of related data is stored. ‘C’ supports a number of functions that
have the ability to perform basic file operations such as
Naming a file
Opening a file
Reading data from a file
Writing data to a file
Closing a file
Defining and Opening a file:
If we want to store data in the file. We must specify certain things about the file. They are
o File name
o Data structure
o Purpose
File Name is a string of characters. It contains two parts namely a primary name and an optional
period with the extension.
Ex: input.c
demo
main.doc
Data structure of a file is defined as FILE. 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.
The general format of declaring and opening a file is as follows.
FILE * fp;
fp=fopen(“file name”, “mode”);
The first statement declares the variable fp as the pointer to the data type FILE.
The second statement uses the function fopen () which is used to create a new file (or) to open an
existing file. It opens the file named file name and assigns an identifier to the pointer fp.
The second statement also specifies the purpose of opening this file. It is represented by using mode.
Mode can be one of the following.
Mode Purpose
r open the file for reading only.
w open the file for writing only
a open the file for appending data to it.
r+ Existing file is opened for both reading and writing
w+ same as w except both for writing and reading
a+ same as a except both for appending and reading
Binary Modes
Mode Purpose
rb file is opened in binary mode for reading
wb file is opened in binary mode for writing
ab file is opened in binary mode for appending data to it.
r+b Existing file is opened for both reading and writing in binary mode
w+b new file is opened for both reading and writing in binary mode
a+b file is opened in append mode and can also be used for writing
purpose in binary mode
Closing a file:
A file must be closed as soon as all operations on it have been completed. This prevents any accidental
misuse of the file. In order to close a file that has been opened we use the function fclose(). The general
format of closing a file is
fclose (file-pointer);
Ex: File *fp;
fp = fopen (“demo.txt “,”r”)
fclose (fp);
C programming does not provide direct support for error handling but being a system programming
language, it provides you access at lower level in the form of return values. Most of the C or even Unix
function calls return -1 or NULL in case of any error and set an error code errno. It is set as a global variable
and indicates an error occurred during any function call. You can find various error codes defined in
<error.h> header file.
So a C programmer can check the returned values and can take appropriate action depending on the return
value. It is a good practice, to set errno to 0 at the time of initializing a program. A value of 0 indicates that
there is no error in the program.
It is possible that an error may occur during I/O operations on a file. Typical error situations include.
Trying to read beyond the end-off-file mark.
Device over flow.
Trying to use a file that has not been opened.
Trying to perform an operation on a file, when the file is opened for another type of operation.
Opening a file with an invalid file name.
Attempting to write to a write-protected file.
If we fail to check, such read & write errors, a program may behave abnormally when an error occurs.
Fortunately, we have two status enquiry library functions. feof() and ferror() that can help us to detect I/O
errors in the files.
Exit():
Generally, a status value of 0 or EXIT_SUCCESS indicates success, and any other value or the constant
EXIT_FAILURE is used to indicate an error. exit() performs following operations.
* Flushes unwritten buffered data.
* Closes all open files.
* Removes temporary files.
* Returns an integer exit status to the operating system.
The C standard atexit() function can be used to customize exit() to perform additional actions at
program termination. When exit() is called, any open file descriptors belonging to the process are closed and
any children of the process are inherited by process 1, init, and the process parent is sent a SIGCHLD signal.
The mystery behind exit() is that it takes only integer args in the range 0 – 255 . Out of range exit values can
result in unexpected exit codes. An exit value greater than 255 returns an exit code modulo 256.
For example, exit 9999 gives an exit code of 15 i.e. (9999 % 256 = 15).
Miscellaneous functions:
Function Description
This function frees the allocated memory by malloc (), calloc (),
realloc () functions
free() and returns the memory to the system.
exit() This function terminates the program and does not return any value
system() This function is used to execute commands outside the C program.
getenv() This function gets the current value of the environment variable
This function displays most recent error that happened during library
perror() function call.