File Handling in C
File Handling in C
Files in C++ are interpreted as a sequence of bytes stored on some storage media.
The data of a file is stored in either readable form or in binary code called as text file or binary file.
Computer programs are associated to work with files as it helps in storing data & information
permanently.
The I/O library manages two aspects- as interface and for transfer of data.
The library predefine a set of operations for all file related handling through certain classes.
A computer file
is stored on a secondary storage device (e.g., disk);
is permanent;
can be used to provide input data to a program or receive output data from a program, or
both;
Streams act as an interface between files and programs. In C++ . A stream is used to refer to the
flow of data from a particular device to the program’s variablesThe device here refers to files,
keyboard, console, memory arrays. In C++ these streams are treated as objects to support
consistent access interface.
They represent as a sequence of bytes and deals with the flow of data.
Every stream is associated with a class having member functions and operations for a particular
kind of data flow.
File -> Program ( Input stream) - reads
All designed into fstream.h and hence needs to be included in all file handling programs.
interactive (iostream)
• Stream is the basic concepts which can be attached to files, strings, console and other devices.
• User can also create their own stream to cater specific device or user defined class.
Streams
A stream is a series of bytes, which act either as a source from which data can be extracted or as
a destination to which the output can be sent. Streams resemble the producer and consumer model
The producer produces the items to be consumed by the consumer. The producer and the
consumers are connected by the C++ operators >> or <<. For instance , the keyboard exhibits the nature
of only a producer,printer or monitor screen exhibit the nature of only a consumer. Whereas , a file
stored on the disk , can behave as a producer or consumer, depending upon the operation initiated on it.
C++ contains several predefined streams that are opened automatically when the execution of a
program starts.
We need to know:
When working with files in C++, the following classes can be used:
ofstream – writing to a file
When ever we include <iostream.h>, an ostream object, is automatically defined – this object is cout.
ostream overloaded the operator >> for standard output.…thus an ofstream object can use methods and
operators defined in ostream.
File Modes
Name Description
ios::app All the date you write, is put at the end of the file.
It calls ios::out
ios::ate All the date you write, is put at the end of the file.
ios::trunc Deletes all previous content in the file. (empties the file)
ios::nocreate If the file does not exist, opening it with the open()
function gets impossible.
Opening a file in ios::out mode also opens it in the ios::trunc mode by default. That is, if the file
already exists, it is truncated
Both ios::app and ios::ate set the pointers to the end of file, but they differ in terms of the types
of operations permitted on a file. The ios::app allows to add data from end of file, whereas
ios::ate mode allows to add or modify the existing data anywhere in the file. In both the cases the
file is created if it is non existent.
The stream classes ifstream and ofstream open files in read and write modes by default.
File pointers
Each file has two associated pointers known as the file pointers.
We can use these pointers to move through the files while reading or writing.
The input pointer is used for reading the contents of a given file location and the output pointer is used
for writing to a given file location.
outFile.close();
Return 0;
If you want to set more than one open mode, just use the OR operator- |. This way:
ios::ate | ios::binary
put(): write a byte and point to the next location for write
#include <iostream>
#include <fstream>
void main()
char ch;
ch='o';
File.close();
int main(void)
ofstream outFile(“fout.txt");
outFile.close();
return 0;
#include <iostream>
#include <fstream>
int main(void)
char ch;
while(!OpenFile.eof())
OpenFile.get(ch);
OpenFile.close();
return 0;
}
#include <iostream>
#include <fstream>
#include <string>
int main(void)
string line;
if(openFile.is_open()){ //
while(!openFile.eof()){
else{
exit(1);}
openFile.close();
return 0;
‘c++’ does not provide standard operators that work on string directly. e.g. we cannot
assign one string to another directly using assignment operator ‘=’, as in case of numeric data
type. e.g.
string1 = “XYZ”
If we want to copy the characters from string2 into string1 then we can make use of
function strcpy() or copy character by character without using function.
Similarly ‘c++’ do not permit comparison of two strings directly. e.g.
if (name1==”ABC”)
So, to compare two strings we can test character by character until a mismatch is found or
one of the string terminates (null character is encountered) or use the function strcmp().
We cannot join two strings by the simple arithmetic operator ‘+’. e.g.
The process of combining two strings is called as concatenation. To combine string1 and
string2, both the strings should be copied into string3 one after the other and the size of the
string3 should be large enough to hold the total characters. Or we can use the built in function
strcat() to join two strings.
String handling functions in ‘C++’: In ‘C++’ there are various built-in functions for string
handling. The ‘C++’ library supports large no.of string handling functions to manipulate the string.
The most commonly used string handling functions are:
The string functions are stored in the header file <string.h>. So you should include this file
at the beginning of the ‘c++’ program.
1) strlen(a) : strlen() function counts and returns the no. of characters in a string. The strlen()
function returns an integer value giving the length of the string. It accepts a single string and
returns an integer by counting number of characters in it. It counts up to the null character, but
the null character itself is not counted in the size. It counts the blank spaces also.
To store the return value of the function strlen(), you should define an ‘int’ variable.
e.g. char a[10]=”CS”;
int i=0;
i=strlen(a);
printf(“\n\tlength of string %s is = %d”,a,i);
It will return ans as 2.
If you want to copy a string than the assignment operator (=) is not allowed, so you should
use the function strcpy(). strcpy() accepts two arguments (i) target string and (ii) the source string.
It copies the source string into the target string. The source string you should pass as second
argument. The first string (argument) is the target string because the copy operation is performed
in the same direction as assignment operator, b = a ; The value of a is copied into b.
The size of the target string (character array) should be large enough to receive the
contents of the source string.
e.g. strcpy(name,”Raja”);
3) strcmp(a,b): strcmp() function is used to compare two strings. It returns an integer value.
It returns the value 0 if both the strings are exactly matching.
If a > b then it will return a +ve integer and if a < b, it will return an negative integer. You
can define an integer variable to store the return value.
The comparison is performed according to the ASCII code of the characters in both the
strings. The numeric value returned is the numeric difference between the first nonmatching
character in the strings.
e.g. strcmp(“Rom”,”Ram”);
will return 14. Because ASCII for ‘o’ is 111 and ASCII for ‘a’ is 97, hence the difference is ‘o’
minus ‘a’ in ASCII code i.e 111 – 97 = 14
4) strrev(a): strrev() function reverse the given string. It accepts only one argument and it stores
the reverse string into the same string variable. So original value of the string variable is lost after
execution of strrev(). So you should first store the original value of the string, using strcpy()
function, in another string variable before passing the string to strrev() function.
5) strcat(a,b): strcat() function joins two strings which is called as string concatenation.
string ‘b’ is appended to string ‘a’. It removes the null character of string ‘a’ and places the string
‘b’ from there. The size of string a should be large enough to hold the final string. e.g.
char a[]=”Good”;
char b[]=”morning”;
strcat(a,b);
cout<<”\n\tstring a= %s”,a;
printf<<“\n\tstring b = %s”,b;
String b = morning
(TABLE OF STRING)
A single dimensional character array is able to store only one name (one string). If
you want to store two or more different names, then you will have to define a two
dimensional character Array. It is treated as a table of strings.
e.g. char capital[5][10];
In above example a two dimensional character array ‘capital’ is defined, it can store list of
capitals, each of length not more than 10 characters. It is able to store five different cities at
memory locations capital[0], capital[1], …. capital[4] and each city name can be up to 10 characters
long.
To read five different city names in above two dimensional character array one ‘for ()’ loop
is sufficient as only one subscript for ‘row’ is needed to be varied. Where as in case of numeric two
dimensional array two ‘for ()’ loops are required to vary two subscripts, one for row and another
for column. In character two dimensional table only one subscript for row is needed to vary,
subscript for column is not required as the conversion specifier %s indicates a ‘string’.
Cin>>a[i];
for (I=0;I<=5;I++)
Cout<<“\n %s”,a[i];
You can initialise the above two dimensional character array as follows:
“Mumbai”
“Delhi”
“Calcutta”
“Bangalore”
A function is a self controlled block of code, written to perform some specific task. A
function is a set of instructions that performs a specified task, which occurs repeatedly in the main
program.
1) Library / built in / Pre Defined Functions: These functions are the functions provided by the
‘c++’ compiler. They are readymade functions provided to carry out various commonly used
operations or calculations. Its code is provided by the ‘c++’ compiler and is stored in various
header files (extension .h).
You can call them any number of times, as and when required in your ‘c++’ program, by
using their proper syntax. You should include the respective header file to run them successfully.
example getch(), clrscr(), sqrt(), sin() …. etc.
2 User defined functions: User defined functions are developed by the programmer for his
own purpose. It contains set of instructions that are needed repeatedly in a program.
return (expression);
Where <parameter list> are the list of parameters that are transferred into the function from the
main program. They are also called as arguments. Parameter list is separated by comma and do
not have terminator ; after parenthesis.
Parameters: They provide data communication between the main program (or calling function)
and the called function.
There are two types of parameters: 1. Actual parameter and 2. Formal parameter.
Actual parameter: They are the parameters transferred from the main program (calling function)
to the called function.
Formal parameter (or Dummy parameter): They are the parameters which receive values from
the actual parameter. They are defined in the called function.
return(<expression>): ‘return’ acts as the closing brace of the function. When return is
encountered the control is immediately passed back to the calling function.
A function may or may not return a value to the calling function. Accordingly a
‘return(<expression>);’ or ‘return;’ can be included in the function.
If a function returns a value to the calling function (or main program) it should include
return(<expression>); where the value of the specified <expression> is returned to the calling
function and then the function is terminated.
#include<conio.h>
#include<stdio.h>
void main()
{ clrscr();
message();
getch();
void message()
printf(“WORK HARD”);
In above example a user defined function message() is declared. The return type is ‘void’
means the function does not return any value. Also there is no <parameter list>, that is it does not
pass any argument while calling.
Passing parameters to a function: In ‘c++’ there are two ways to pass the parameters to a
function: 1. Call by value 2. Call by reference
1. Call by value: In this method the value of actual parameters is copied into the formal
parameters of the function. Here, the changes in the formal(dummy) parameter do not affect the
actual parameters.
2. Call by reference: In this method the address of actual parameters (of calling function) is
copied into the formal parameters (of the called function). So the changes made to the dummy
parameters inside the called function will affect the variables of the main program (calling
function).
Scope of Varaibles:
Scope of variables specifies the availability of variables within the program. Variables have
two type of scope: 1. Local and 2. Global
Local Variables: The variables which are declared inside a function, are called as local
variables. Local variable means they can be used only inside the function where they are defined.
If you try to use them in another function you will receive error message. Or if you define a
variable with the same name in any other function, they are treated as two different variables local
to that respective function.