0% found this document useful (0 votes)
22 views17 pages

File Handling in C

Uploaded by

Rashmi Agrawal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
22 views17 pages

File Handling in C

Uploaded by

Rashmi Agrawal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 17

File handling in C++

Using Input/Output Files

 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.

 The flow of data from any source to a sink is called as a stream

 Computer programs are associated to work with files as it helps in storing data & information
permanently.

 File - itself a bunch of bytes stored on some storage devices.

 In C++ this is achieved through a component header file called fstream.h

 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;

 must be opened before it is used.

General File I/O Steps


 Declare a file name variable Associate the file name variable with the disk file name

 Open the file

 Use the file

 Close the file

 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

 Program -> File (Output stream) – write

 All designed into fstream.h and hence needs to be included in all file handling programs.

 Diagrammatically as shown in next slide

stream - a sequence of characters

 interactive (iostream)

• cin - input stream associated with keyboard.

• cout - output stream associated with display.


 file (fstream)

• ifstream - defines new input stream (normally associated with a file).

• ofstream - defines new output stream (normally associated with a file).

• Stream of bytes to do input and output to different devices.

• 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.

1) cin :standard input (usually keyboard) corresponding to stdio in C

2) cout :standard output (usually screen) corresponding to stdout in C

3) cerr :standard error output (usually screen) corresponding to stderr in C

4) clog : A fully buffered version of cerr (No C equivalent)

 Convenient way to deal large quantities of data.

 Store data permanently (until file is deleted).

 Avoid typing data into program multiple times.

 Share data between programs.

 We need to know:

 how to "connect" file to program

 how to tell the program to read data

 how to tell the program to write data


 error checking and handling EOF

Classes for Stream I/O in C++

ios is the base class.

istream and ostream inherit from ios

ifstream inherits from istream (and ios)

ofstream inherits from ostream (and ios)

iostream inherits from istream and ostream (& ios)

fstream inherits from ifstream, iostream, and ofstream

When working with files in C++, the following classes can be used:
ofstream – writing to a file

ifstream – reading for a file

fstream – reading / writing

When ever we include <iostream.h>, an ostream object, is automatically defined – this object is cout.

ofstream inherits from the class ostream (standard output class).

ostream overloaded the operator >> for standard output.…thus an ofstream object can use methods and
operators defined in ostream.
File Modes

Name Description

ios::in Open file to read

ios::out Open file to write

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.

It does not call ios::out

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.

ios::noreplace If the file exists, trying to open it with the open()

function, returns an error.

ios::binary Opens the file in binary mode.

 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 mode ios::app can be used only with output files

 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.

One of them is called the input pointer or get pointer.


The get pointer specifies a location from which the current reading operation is initiated
Other is called the output pointer or put pointer.
The put pointer specifies a location from where the current writing operation is initiated

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.

Functions for manipulation of file pointers


seekg() Moves get pointer (input) to a specified location.
seekp() Moves put pointer (output) to a specified location.
tellg() Gives the current position of the get pointer.
tellp() Gives the current position of the put pointer.

File Open Mode


#include <fstream>
int main(void)

ofstream outFile("file1.txt", ios::out);

outFile << "That's new!\n";

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

Dealing with Binary files


 Functions for binary file handling

get(): read a byte and point to the next byte to read

put(): write a byte and point to the next location for write

read(): block reading

write(): block writing

flush():Save data from the buffer to the output file.

Binary File I/O Examples


//Example 1: Using get() and put()

#include <iostream>

#include <fstream>

void main()

fstream File("test_file",ios::out | ios::in | ios::binary);

char ch;

ch='o';

File.put(ch); //put the content of ch to the file

File.seekg(ios::beg); //go to the beginning of the file


File.get(ch); //read one character

cout << ch << endl; //display it

File.close();

File I/O Example: Writing


#include <fstream>

using namespace std;

int main(void)

ofstream outFile(“fout.txt");

outFile << "Hello World!";

outFile.close();

return 0;

File I/O Example: Reading

#include <iostream>

#include <fstream>

int main(void)

ifstream openFile(“data.txt"); //open a text file data.txt

char ch;

while(!OpenFile.eof())

OpenFile.get(ch);

cout << ch;

OpenFile.close();

return 0;
}

#include <iostream>

#include <fstream>

#include <string>

int main(void)

ifstream openFile(“data.txt"); //open a text file data.txt

string line;

if(openFile.is_open()){ //

while(!openFile.eof()){

getline(openFile,line);//read a line from data.txt and put it in a string

cout << line;

else{

cout<<“File does not exist!”<<endl;

exit(1);}

openFile.close();

return 0;

String handling in ‘c++’:

‘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”

OR string1 = string2 are both invalid statements.

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”)

OR if (name1 == name2) are both invalid statements.

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.

string3 = string1 + string2;

string3 = string1 + “Good”; are both invalid statements.

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:

Sr. String Purpose


No. Function
1 strlen() Find length of the string
2 strcpy() Copy one string to another
3 strcmp() Compare two strings
4 strrev() Reverse a string
5 strcat() Concatenate or combine two strings

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.

2) strcpy(b,a): strcpy() function copies string ‘a’ into string ‘b’.

where a is source string and b is target string.

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”);

will assign the string “Raja” to the string variable name.

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;

It will print: string a= Goodmorning

String b = morning

TWO DIMENSIONAL CHARACTER ARRAY

(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’.

e.g. for (i=0;i<5;i++)

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:

e.g. char capital[5][10] = { “Chennai”

“Mumbai”

“Delhi”

“Calcutta”

“Bangalore”

USER DEFINED FUNCTION

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.

There are two types of functions:

1) Library Functions (also called as built in or predefined functions) and


2) User defined functions.

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.

Advantages of user defined functions:

 The length of the main program is reduced.


 They avoid repeated typing of certain instructions.
 The user defined function can be used in many other source programs.
 It is easy to locate and debug an error.
 It enables to develop a modular program using top-down programming approach.
 They enable a programmer to build customized library.

Format: <return type> <function name> ( <parameter list> )

{ <local variable declaration>;

< body of function (set of instructions)>

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.

example-1: (function with no argument and no return value)

#include<conio.h>

#include<stdio.h>

void main()

{ clrscr();

void message(); // declaration of function

printf(“\n\t DO NOT STOP”);

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).

To pass the address of the actual parameters pointers are used.

LOCAL and GLOBAL VARIABLES:

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.

You might also like