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

Files in C++: Opening A File

Files in C++ are used to store data permanently. The fstream library contains classes like ifstream for reading from files and ofstream for writing to files. To open a file, a file stream object must be declared and opened using a constructor or open() function. Files can be opened in text mode or binary mode. Text files may undergo character translations while binary files are read and written as-is. Reading/writing involves declaring a file stream, opening the file, reading/writing data using operators or functions, and closing the file.

Uploaded by

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

Files in C++: Opening A File

Files in C++ are used to store data permanently. The fstream library contains classes like ifstream for reading from files and ofstream for writing to files. To open a file, a file stream object must be declared and opened using a constructor or open() function. Files can be opened in text mode or binary mode. Text files may undergo character translations while binary files are read and written as-is. Reading/writing involves declaring a file stream, opening the file, reading/writing data using operators or functions, and closing the file.

Uploaded by

Avi Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Files in c++

When a program runs, the data is in the memory but when it ends or the computer shuts
down, it gets lost. To keep data permanently, we need to write it in a file.
File is used to store data. In this topic, you will learn about reading data from a file and
writing data to the file.
fstream is another C++ standard library like iostream and is used to read and write on
files.
These are the data types used for file handling from the fstream library:
These are the data types used for file handling from the fstream library:

Data
Description
type

ofstream It is used to create files and write on files.

ifstream It is used to read from files.

It can perform the function of both ofstream and ifstream which means it
fstream
can create files, write on files, and read from files.

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 object is used to open a file for reading purpose only.
A file can be opened in two ways:
i)using constructor function of the class.
ii) Using member function open() of the class.
The first method is preferred when a single file is used with a stream. However, for managing
multiple files with the same stream, the second method is preferred.

Opening File Using Constructors

The constructors of stream classes (ifstream, ofstream, or fstream) are used to initialize
file stream objects with the filenames passed to them. This is carried out as explained
here:
To open a file named myfile as an input file we shall create a file stream object of input
type i.e., ifstream type. Here is an example:

ifstream fin("myfile", ios::in) ;


The above given statement creates an object, fin, of input file stream. The object name
is a user-defined name .After creating the ifstream object fin, the file myfile is opened
and attached to the input stream, fin.

ofstream fout("myfile", ios::out) ;

The above given statement creates an object, fout, of output file stream.

Opening Files Using Open() Function

There may be situations requiring a program to open more than one file. The strategy
for opening multiple files depends upon how they will be used. To use this approach,
declare a stream object without initializing it, then use a second statement to associate
the stream with a file. For example,

ifstream fin; // create an input stream


fin.open("myfile ", ios::in); // associate fin stream with file

ofstream fout; // create an output stream


fout.open("myfile ", ios::out); // associate fout stream with file

List of File Modes in C++

Following table lists the filemodes available in C++ with their meaning :

Stream
Constant Meaning
Type

ios :: in It opens file for reading, i.e., in input mode. ifstream

It opens file for writing, i.e., in output mode.


This also opens the file in ios :: trunc mode, by default.
ios :: out ofstream
This means an existing file is truncated when opened,
i.e., its previous contents are discarded.

This seeks to end-of-file upon opening of the file. ofstream


ios :: ate
I/O operations can still occur anywhere within the file. ifstream

This causes all output to that file to be appended to the end.


ios :: app ofstream
This value can be used only with files capable of output.

This value causes the contents of a pre-existing file by the


ios :: trunc same name ofstream
to be destroyed and truncates the file to zero length.
This cause the open() function to fail if the file does not
ios :: nocreate already exist. ofstream
It will not create a new file with that name.

This causes the open() function to fail if the file already


ios :: exists.
ofstream
noreplace This is used when you want to create a new file and at the
same time.

This causes a file to be opened in binary mode.


By default, files are opened in text mode.
When a file is opened in text mode,
ofstream
ios :: binary various character translations may take place,
ifstream
such as the conversion of carriage-return into newlines.
However, no such character translations occur in file opened
in binary mode.

Closing a file
C++ automatically close and release all the allocated memory. But a programmer
should always close all the opened files. The syntax for closing a file is:
stream_object.close();
for example

fin.close() ;
fout.close() ;

C++ Opening and Closing a File Example

#include <iostream.h>
#include <fstream.h>
int main()
{
ofstream file;
file.open ("example.txt");
file.close();
return 0;
}
Text files
Text file streams are those where the ios::binary flag is not included in their opening mode.

These files are designed to store text and thus all values that are input or output from/to them can

suffer some formatting transformations, which do not necessarily correspond to their literal binary
value.

Writing in a text file

Steps to create (or write to) file:

1. Declare a stream variable name:

//each file has its own


ofstream fout; stream buffer

ofstream is short for output file stream


fout is the stream variable name

2. Open the file:

fout.open("scores.dat", ios::out);

fout is the stream variable name previously declared


"scores.dat" is the name of the file
ios::out is the steam operation mode

3. Write data to the file:

fout<<grade<<endl;
fout<<"Mr. Spock\n";

4. Close the file: fout.close( );

Program to write in a text file


#include <iostream>
#include <fstream>
int main ()
{
ofstream fout;
fout.open("example.txt");
if (fout.is_open())
{
fout << "This is a line.\n";
fout << "This is another line.\n";
fout.close();
}
else cout << "Unable to open file";
return 0;
}
Reading from a text file

Steps to use (or read) a sequential access file:

1. Declare a stream variable name:

//each file has its own


ifstream fin; stream buffer

ifstream is short for input file stream


fin is the stream variable name

2. Open the file:

fin.open("myfile.dat", ios::in);

fin is the stream variable name previously declared


"myfile.dat" is the name of the file
ios::in is the steam operation mode

3. Read data from the file:


You MUST be aware of the necessary variable types.

//to read one number and //to read one number and
//one string variable //one string variable
int number; int number;
apstring item; apstring item, dummy;
fin>>number>>item; getline(fin, item);
fin>>item;
This format is OK only if the getline(fin,dummy);
string variable is
a singleword. This format is needed if the
string variable contains
whitespace.

4. Close the file: fin.close( );

Program to read from a text file


#include <iostream>
#include <fstream>
#include <string>
int main ()
{
int N=80;
char line[N];
ifstream fin;
fin.open ("example.txt");
while (fin)
{
fin.getline(line,N);
cout << line << '\n';
}
myfile.close();
return 0;
}
Binary Files

When data is stored in a file in the binary format, reading and writing data is faster because no
time is lost in converting the data from one format to another format. Such files are called
binary files. These file streams are those where the ios::binary flag is included in their opening
mode. For binary files, reading and writing data with the extraction and insertion operators
(<< and >>) and functions like getline is not efficient. File streams include two member
functions specifically designed to read and write binary data sequentially: write and read. The
first one (write) is a member function of ostream (inherited by ofstream). And read is a member
function of istream (inherited by ifstream). Objects of class fstream have both. Their prototypes
are:

write ( memory_block, size );


read ( memory_block, size );

Where memory_block is of type char* (pointer to char), and represents the address of an array
of bytes where the read data elements are stored or from where the data elements to be
written are taken. The size parameter is an integer value that specifies the number of
characters to be read or written from/to the memory block.

Program to write and read an object in, from binary file using write()
and read()
#include<iostream>
#include<fstream>
#include<cstdio>

class Student
{
int admno;
char name[50];
public:
void setData()
{
cout << "\nEnter admission no. ";
cin >> admno;
cout << "Enter name of student ";
cin.getline(name,50);
}
void showData()
{
cout << "\nAdmission no. : " << admno;
cout << "\nStudent Name : " << name;
}

};

int main()
{
ofstream outFile;
outFile.open("student.dat", ios::binary | ios::app);

Student obj;
obj.setData();

outFile.write((char*)&obj, sizeof(obj));//writing object in binary file

outFile.close();

//open again in reading mode


ifstream inFile;
inFile.open("student.dat", ios::binary);

while(inFile.read((char*)&obj, sizeof(obj)))
{
obj.showData();
}

inFile.close();
return 0;
}

File Pointers
The C++ input and output system manages two integer values associates with a file.
These are:

• get pointer – specifies the location in a file where the next read operation will occur.
• put pointer – specifies the location in a file where the next write operation will occur.
In other words, these pointers indicate the current positions for read and write operations,
respectively. Each time an input or an output operation takes place, the pointers are automatically
advances sequentially. The seekg() and tellg() functions allow you to set and examine the
get_pointer, and the seekp() and tellp() functions perform these operations on the put_pointer.

The most common forms of these functions are :

istream & seekg(long); Form 1


seekg()
istream & seekg(long, seek_dir); Form 2

ofstream & seekp(long); Form 1


seekp()
ofstream & seekp(long, seek_dir); Form 2

tellg() long tellg()

tellp() long tellp()


The tellg() and tellp() functions can be used to find out the current position of the get
and put file pointers respectively in a file.

The The seekg() or seekp(), when used according to Form 1, then it moves the get_pointer or
put_pointer to an absolute position.for example

ifstream fin;
ofstream fout;
fin.seekg(30);// will move the get_pointer to byte number 30 in the file
fout.seekp(30);// will move the put_pointer to byte number 30 in the file

When seekg() or seekp() function is used according to Form 2, then it moves the
get_pointer or put_pointer to a position relative to the current position, following the
definition of seek_dir. Since, seek_dir is an enumeration defined in the header file
iostream.h, that has the following values:

ios::beg, // refers to the beginning of the file


ios::cur, // refers to the current position in the file
ios::end} // refers to the end of the file

Here is an example.

fin.seekg(30, ios::beg); // go to byte no. 30 from beginning of file


linked with fin
fin.seekg(-2, ios::cur); // back up 2 bytes from the current position of
get pointer
fin.seekg(0, ios::end); // go to the end of the file
fin.seekg(-4, ios::end); // backup 4 bytes from the end of the file

You might also like