Nothing Special   »   [go: up one dir, main page]

Chapter 4 - File

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Programming Fundamentals II

Chapter Four
File
So far, we have been using the iostream standard library, which provides cin and cout
object for reading from standard input keyboard and for writing to standard output
console screen respectively. In this section, the method of how to read from a file and
write to a file will be discussed.
Note:- In read operation, a file is considered as standard input and in write operation a
file is used as standard output. In this approach, secondary storage devices are used as
input or output terminal since file is considered to be the content of these devices.

This approach requires another standard C++ library like


 ofstream:- This data type(object) represents the output file stream and is used to
create files and to write information to files.
 ifstream: This data type(object) represents the input file stream and is used to read
information from files.
 fstream This data type represents the file stream generally, and has the
capabilities of both ofstream and ifstream which means it can create files, write
information to files, and read information from files.

To perform file processing in C++, header files <iostream> and <fstream> must be
included in your C++ source file.
1.1. Category of File
Files in computer systems can be classified into Text file and Binary file. Text files are
those file with specified format or file extension.
Example : .txt, .doc.
This category of files contains printable ASCII characters. The content of this file can be
accessed sequentially. On the other hand files can be stored in binary format that is in
0/1. This category of files can be accessed randomly.

1.2. Opening a File

A file must be opened before you can read from it or write to it. Either ofstream or fstream
object may be used to open a file for writing. And ifstream or fstream object is used to
open a file for reading purpose only. Following is the standard syntax for open() function,
which is a member of fstream, ifstream, and ofstream objects.
void open(const char *filename, ios::openmode mode);
Here, the first argument specifies the name and location of the file to be opened and the
second argument of the open() member function defines the mode in which the file
should be opened.
The possible file opening modes are summarized in table below

Page 1
Programming Fundamentals II

File open mode parameter Meaning


ios::app Append to end of file
ios::ate go to end of file on opening
ios::binary file open in binary mode
ios::in open file for reading only
ios::out open file for writing only
ios::nocreate open fails if the file does not
exist
ios::noreplace open fails if the file already exist
ios::trunc delete the contents of the file if it
exist

1.3. Closing a File

When a C++ program terminates it automatically flushes all the streams, release all the
allocated memory and close all the opened files. But it is always a good practice that a
programmer should close all the opened files before program termination.

1.4. Writing to a File

While doing C++ programming, you write information to a file from your program using
the stream insertion operator (<<) just as we use that operator to output information to
the screen. The only difference is that you use an ofstream or fstream object instead of the
cout object.
The ofstream object outfile is used in the following example to write to the file located at
"C:/Users/UserName/Desktop/cd/adfile.doc" directory.
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
char data[100];
// open a file in write mode.
ofstream outfile;/*the ofstream object outfile used to write to a
file*/
outfile.open("C:/Users/UserName/Desktop/cd/adfile.doc",ios::app);
//uesd to open the file
if(outfile.is_open())
{
cout << "Writing to the file" << endl;
outfile<<"....Hello world.....\n";//this line writes to file
cout << "Enter your name: ";

Page 2
Programming Fundamentals II

cin.getline(data, 100);
// write inputted data into the file.
outfile << data << endl;
cout << "Enter your age: ";
cin >> data;
cin.ignore();
// again write inputted data into the file.
outfile << data << endl;
cout<<"The file is succesfully opend"<<endl;
// close the opened file.
outfile.close();
}
else
{
cout<<"unable to open the file"<<endl;
}
return 0;
}
Note:- This program opens the file and writes the contents with the ofstream object the
close the file finally.

1.5. Reading from a File

You read information from a file into your program using the stream extraction operator
(>>) just as you use that operator to input information from the keyboard. The only
difference is that you use an ifstream or fstream object instead of the cin object.
// read the data from the file and display it word by word.
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
char data[100];
ifstream infile;
int i=0;
infile.open("C:/Users/UserName/Desktop/afile.doc",ios::in);
//directory
cout << "Reading from the file" << endl;
string str;
while(infile>>data)
{
// read the data from the file and display it word by word.
cout << data<< endl;
}

Page 3
Programming Fundamentals II

// close the opened file.


infile.close();
return 0;
}
//Reading file line by line using the getline() function
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
char data[100];
ifstream infile;
int i=0;
infile.open("C:/Users/UserName/Desktop/afile.doc",ios::in);
cout << "Reading from the file" << endl;
string str;
while(!infile.eof()){
getline(infile,str);//read the file and display it line by line.
cout << str<< endl; }
// close the opened file.
infile.close();
return 0;
}
Note:- in reading file from a file the end of file can be detected using Boolean functions
like eof(), fail(),good() as shown above within while() loop.

1.6. File Position Pointers


Both istream and ostream provide member functions for repositioning the file-position
pointer.
These member functions are seekg " seekget " for istream and seekp " seekput " for
ostream.
The argument to seekg and seekp normally is a long integer. A second argument can be
specified to indicate the seek direction. The seek direction can be ios::beg thedefault for
positioning relative to the beginning of a stream, ios::cur for positioning relative to the
current position in a stream or ios::end for positioning relative to the end of a stream.The
file-position pointer is an integer value that specifies the location in the file as a number
of bytes from the file's starting location. Some examples of positioning the "get" file-
position pointer are:
// position to the nth byte of fileObject (assum es
ios::beg)
fileObject.seekg( n );
// position n bytes forward in fileObject
fileObject.seekg( n, ios::cur );

Page 4
Programming Fundamentals II

// position n bytes back from end of fileObject


fileObject.seekg( n, ios::end );
// position at end of fileObject
fileObject.seekg( 0, ios::end );
Using these file-position pointers we can find the file size of a given file as shown in the
following example
// obtaining file size
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
long begin,end;
ifstream myfile;
myfile.open("C:/Users/UserName/Desktop/afile.doc");
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
cout<<begin<<", "<<end<<endl;
cout << "size is: " << (end-begin) << " bytes.\n";
return 0;
}
When the above program is executed, it calculates the number of characters in the file
located at "C:/Users/UserName/Desktop/afile.doc" including the spaces.

Page 5

You might also like