0% found this document useful (0 votes)
10 views55 pages

File - Stream

The document provides an overview of file handling in C++ using the fstream library, detailing how to read from and write to files with various data types. It explains the functions for file operations, error handling, and the use of file pointers and manipulators. Additionally, it discusses the structure of .dat files and their common usage in data storage.

Uploaded by

rule03072004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODP, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views55 pages

File - Stream

The document provides an overview of file handling in C++ using the fstream library, detailing how to read from and write to files with various data types. It explains the functions for file operations, error handling, and the use of file pointers and manipulators. Additionally, it discusses the structure of .dat files and their common usage in data storage.

Uploaded by

rule03072004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODP, PDF, TXT or read online on Scribd
You are on page 1/ 55

Files and Streams

Prof. Deepali Ahir


Prof. Deepali Ahir
Prof. Deepali Ahir
The fstream library allows us to work with files.

To use the fstream library, include both the
standard <iostream> AND the <fstream>
header file:
Example

#include <iostream>

#include <fstream>

Prof. Deepali Ahir



How to read and write from a file

Requires another standard C++ library called
fstream.

Defines three new data types:

ofstream: Represents the output file stream and is
used to create files and to write information to files

ifstream : Represents the input file stream and is
used to read information from files.

fstream : Represents the file stream, and has the
capabilities of both ofstream and ifstream, it can
create files, write information to files, and read
information from files.
Prof. Deepali Ahir
Classes for File Stream Operations
These classes are designed to manage the disk files and are declared in fstream.

Prof. Deepali Ahir


File handling operations

Naming a file

Opening a file

Reading data from file

Writing data into file

Closing a file

Prof. Deepali Ahir


Functions
Functions Operation
open() To create a file
close() To close an existing file
get() Read a single character from a
file
put() write a single character in file.
read() Read data from file
write() Write data into file.

Prof. Deepali Ahir


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

Syntax:
void open(const char *filename, ios::openmode mode);


Ex: ofstream outfile; // create stream
outfile . open ("data1.txt"); // connect stream to data1

Prof. Deepali Ahir


File Opening mode
Mode Meaning Purpose

ios :: out Write Open the file for write only.

ios :: in read Open the file for read only.

ios :: app Appending Open the file for appending


data to end-of-file.

ios :: ate Appending take us to the end of the file


when it is opened.

Ios::trunc truncate Any contents that existed in


Prof. Deepali Ahir
the file before it is open are
discarded.

Ex1:
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );


Ex2:
fstream afile;
afile.open("file.dat", ios::out | ios::in );

Prof. Deepali Ahir


#include <iostream>
#include <fstream>
using namespace std;

int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}

Prof. Deepali Ahir


#include <iostream>
#include <fstream>
using namespace std;

int main () {
ofstream myfile ("example1.txt");
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";
return 0;
} Prof. Deepali Ahir
Errors

a file being opened for reading might not exist.

a file name used for a new file may already
exist.

an attempt could be made to read past the end-
of-file.

invalid operation may be performed.

might not be enough space in the disk for
storing data.

Prof. Deepali Ahir


Stream Errors

The 'errors' or 'signals' (e.g., reaching the end
of the file) occur when a stream encounters
something it didn't expect.

Detailed status of the stream can be obtained
using functions:

good()

bad()

fail()

eof()

clear() Prof. Deepali Ahir
The current state of the I/O system is held in an integer, in
which the following flags are encoded :

Name Meaning

eofbit 1 when end-of-file is encountered, 0


otherwise.

failbit 1 when a non-fatal I/O error has occurred,


0 otherwise

badbit 1 when a fatal I/O error has occurred, 0


otherwise

goodbit 0 value

Prof. Deepali Ahir


good() returns true when everything is okay.

bad() returns true when a fatal error has occurred.

fail() returns true after an unsuccessful stream operation like an


unexpected type of input being encountered.

eof() returns true when the end of file is reached.

clear() will reset the stream and clear the error, which is necessary
to perform any further IO on the stream.

Prof. Deepali Ahir



The above functions can be summarized as:

eof() returns true if eofbit is set;

bad() returns true if badbit is set.

The fail() function returns true if failbit is set;

the good() returns true there are no errors.

Otherwise, they return false.

Prof. Deepali Ahir


Iostate Indicates functions to check state flags
value

goodbit No Errors good() eof() fail() bad()

eofbit EOF reached on i/p T F F F


operation

failbit Logical error on i/o F T F F


opeartion

badbit R/w error on i/o F F T T


operation

Prof. Deepali Ahir


Prof. Deepali Ahir
#include <iostream> // std::cout
#include <fstream> // std::fstream
int main () {
char buffer [80];
std::fstream myfile;
myfile.open ("test.txt",std::fstream::in);
myfile << "test";
if (myfile.fail())
{
std::cout << "Error writing to test.txt\n";
myfile.clear();
}
myfile.getline (buffer,80);
std::cout << buffer << " successfully read from file.\n";
return 0; Prof. Deepali Ahir

In this example, myfile is open for input operations, but we
perform an output operation on it, so failbit is set.

The example calls then clear in order to remove the flag
and allow further operations like getline to be attempted
on myfile.

Output:
Error writing to test.txt
successfully read from file.

Prof. Deepali Ahir


#include <iostream>
#include <sstream>
void print_state (const std::ios& stream) {
std::cout << " good()=" << stream.good();
std::cout << " eof()=" << stream.eof();
std::cout << " fail()=" << stream.fail();
std::cout << " bad()=" << stream.bad();
}
int main () {
std::stringstream stream;

stream.clear (stream.goodbit);
std::cout << "goodbit:"; print_state(stream); std::cout << '\n';
stream.clear (stream.eofbit);
std::cout << " eofbit:"; print_state(stream); std::cout << '\n';
stream.clear (stream.failbit);
std::cout << "failbit:"; print_state(stream); std::cout << '\n';
stream.clear (stream.badbit);
std::cout << " badbit:"; print_state(stream); std::cout << '\n';
stream.clear (stream.goodbit);
std::cout << "goodbit:"; print_state(stream); std::cout << '\n';
return 0; Prof. Deepali Ahir
}
Output :
goodbit: good()=1 eof()=0 fail()=0 bad()=0
eofbit: good()=0 eof()=1 fail()=0 bad()=0
failbit: good()=0 eof()=0 fail()=1 bad()=0
badbit: good()=0 eof()=0 fail()=1 bad()=1

Prof. Deepali Ahir


#include <iostream> // std::cout
#include <fstream> // std::fstream
#include <sstream>
int main () {
std::stringstream stream;
char buffer [80];
std::fstream myfile;
myfile.open ("test.txt",std::fstream::in);
myfile << "test";
if (myfile.fail())
{
std::cout << "Error writing to test.txt\n";
myfile.clear();
}
stream.clear (stream.badbit);
std::cout << " good()=" << stream.fail();
std::cout << " good()=" << stream.bad();
myfile.getline (buffer,80);
std::cout << buffer << " successfully read from file.\n";
Prof. Deepali Ahir
return 0;
Output :
Error writing to test.txt
fail()=1 bad()=1test successfully read from file.

Prof. Deepali Ahir


File Pointers and Manipulators


All file objects hold two file pointers that are
associated with the file.


Two pointers provides two integer values.


Integer values indicate the exact position of the
file pointers in the number of bytes in the file.


The read and write Prof.
operations
Deepali Ahir
are carried out at
the location pointed by these file pointers

Get pointer(input pointer)

Put pointer(output pointer)


Get pointer helps in reading a file from the
given loaction.

Put pointer helps in writting a data in the file at
the specified location.

Get and put pointers are by default set at the
beginning of file.

Prof. Deepali Ahir


Prof. Deepali Ahir
Prof. Deepali Ahir

seekg()
It is used to move the get pointer to a desired
location with respect to a reference point.

Syntax:file_pointer.seekg (number of bytes ,Reference point);

Example: fin.seekg(10,ios::beg);


tellg()
It is used to know where the get pointer is in a
file.

Syntax: file_pointer.tellg();

Example: int posn = fin.tellg();
Prof. Deepali Ahir

Seekp()
It is used to move the put pointer to a desired
location with respect to a reference point.

Syntax:file_pointer.seekp(number of bytes ,Reference point);

Example: fout.seekp(10,ios::beg);


tellp()

It is used to know where the put pointer is in a
file.

Syntax: file_pointer.tellp();

Example: int posn=fout.tellp();
Prof. Deepali Ahir
Pointer offset calls
Seek call(Reference Points) Actions
fout.seekg(0, ios::beg) Go to start

fout.seekg(0, ios::cur) Stay at the current position

fout.seekg(0, ios::end) Go to the end of file


fout.seekg(m, ios::beg) Move to (m+1)th byte in the file
fout.seekg(m, ios::cur) Go forward by m bytes from the
current position

fout.seekg(-m, ios::cur) Go backward by m bytes from the


current position
fout.seekg(-m, ios::end) Go backward by m bytes from the
current position

Prof. Deepali Ahir


get and put stream positioning

Internal stream positions point to the locations
within the stream where the next reading or
writing operation is performed.

ifstream, like istream, keeps an internal get
position with the location of the element to be
read in the next input operation.

ofstream, like ostream, keeps an internal put
position with the location where the next
element has to be written.

Finally, fstream, keeps both, the get and the
put position, like iostream.
Prof. Deepali Ahir
tellg() current get position(read)

tellp() current put position(write)

seekg() change the location of the get position

seekp()
change the location of the put position

Prof. Deepali Ahir



seekg ( position );

seekp ( position );

seekg ( offset, direction );

seekp ( offset, direction );
● ios::beg offset counted from the beginning of
the stream

ios::cur offset counted from the current


position

ios::end offset counted from the end of the


stream

Prof. Deepali Ahir


Sequential input, output operations


Put(), get() for handling single character at a time.


Write(), read() for handling block of data.

Syntax:

file_obj.read(add_of_obj, size_of_obj);

file_obj.write(add_of_obj, size_of_obj);

Prof. Deepali Ahir



The write() function is used to write object or
record (sequence of bytes) to the file.

A record may be an array, structure or class.
Syntax:
fstream fout;
fout.write( (char *) &obj, sizeof(obj) );

&obj : Initial byte of an object stored in memory.

sizeof(obj) : size of object represents the total
number of bytes to be written from initial byte.

Prof. Deepali Ahir



The read() function is used to read object
(sequence of bytes) to the file.

Syntax :
fstream fin;
fin.read( (char *) &obj, sizeof(obj) );

&obj : Initial byte of an object stored in file.

sizeof(obj) : size of object represents the total
number of bytes to be read from initial byte.

The read() function returns NULL if no data
read.

.dat, .txt, .exe, .out
Prof. Deepali Ahir
What is a DAT file?

Many different programs use the .dat file extension.
When you see a file on your computer with the .dat
extension, all it really means is that the file contains
some typeof computer data.

There is really no way to tell what type of data the file
contains unless you open it.

The problem is, unless you know where the file
originated from, the data contained within the .dat file be
hard to decipher.

They DAT file format is, in fact, one of the most common
file formats in existence.

It is very often used to save attachments that have been
sent from an Outlook email client

Prof. Deepali Ahir



A DAT file you receive as an email attachment usually comes in the form of a winmail.dat or
ATT0001.dat file. These types of DAT files are probably malformed attachments from a Microsoft
email client like Outlook, Outlook Express, Windows Live Mail, or Microsoft Exchange.

In this scenario, you should save the DAT file to your computer and either upload it to
Winmaildat.com or import it into Winmail Opener to extract out the actual attachment.

That attachment might ultimately end up being any other kind of file, like a document, an image, etc.

Prof. Deepali Ahir



C++ program to write and read text in/from file.
O/P : File created successfully.
File content: ABCD.

C++ program to write and read object using
read and write function
O/p : File created successfully.
Enter name:Mike
Enter age:21
File saved and closed succesfully.
Name:Mike,Age:21

C++ program to demonstrate example of tellg()
and tellp() function.

Prof. Deepali Ahir


Current position is: 26
After opening file position is: 0
At position : 0 Character "A"
At position : 1 Character "B"
At position : 2 Character "C"
At position : 3 Character "D"
At position : 4 Character "E"
At position : 5 Character "F"
At position : 6 Character "G"
At position : 7 Character "H"
At position : 8 Character "I"
At position : 9 Character "J"
At position : 10 Character "K"
At position : 11 Character "L"
At position : 12 Character "M"
At position : 13 Character "N"
At position : 14 Character "O"
At position : 15 Character "P"
At position : 16 Character "Q"
At position : 17 Character "R"
At position : 18 Character "S"
At position : 19 Character "T"
At position : 20 Character "U"
At position : 21 Character "V"
At position : 22 Character "W"
At position : 23 Character "X" Prof. Deepali Ahir
At position : 24 Character "Y"
At position : 25 Character "Z"
Write a c++ program to find the beginning
position of the fine, end position of the file
and size of the text file

Prof. Deepali Ahir


#include <iostream>
#include <fstream>
using namespace std;

int main () {
int begin,end;
fstream myfile ("example.txt", ios::out);
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
cout << "begining of file is at: "<< begin <<endl;
cout << "End of file is at: " << end<<endl;
cout << "size is: " << (end-begin) << " bytes.\n";
return 0;
Prof. Deepali Ahir
}
Output :-
begining of file is at: 0
End of file is at: 204
size is: 204 bytes.

Prof. Deepali Ahir


Command line arguments in C/C++
int main() int main(int argc, char *argv[ ])
{ {
/* ... */ /* ... */
} }

We can also give command-line arguments in C++.

Command-line arguments are given after the name
of the program in command-line shell of Operating
Systems.

To pass command line arguments, we typically
define main() with two arguments :

first argument is the number of command line
arguments and second is list of command-line
Prof. Deepali Ahir
arguments.
argc (ARGument Count)

It is int and stores number of command-line
arguments passed by the user including the name of
the program. So if we pass a value to a program,
value of argc would be 2 (one for argument and one
for program name)

The value of argc should be non negative.
argv(ARGument Vector)

It is an array of character pointers listing all the
arguments.

If argc is greater than zero,the array elements from
argv[0] to argv[argc-1] will contain pointers to strings.

Argv[0] is the name of the program , After that till
argv[argc-1] every Prof.
element
Deepali Ahir is command -line
arguments.
#include <iostream>
using namespace std;

int main(int argc, char** argv)


{
cout << "You have entered " << argc
<< " arguments:" << "\n";

for (int i = 0; i < argc; ++i)


cout << argv[i] << "\n";

return 0; Prof. Deepali Ahir

}
Output:-
admin1@admin1:~$ g++ command.cpp
admin1@admin1:~$ ./a.out deepali ahir
You have entered 3 arguments:
./a.out
deepali
ahir

Prof. Deepali Ahir


Remember

They are passed to main() function.

They are parameters/arguments supplied to the
program when it is invoked.

They are used to control program from outside
instead of hard coding those values inside the
code.

argv[argc] is a NULL pointer.

argv[0] holds the name of the program.

argv[1] points to the first command line
argument and argv[n] points last argument.
Prof. Deepali Ahir
Write a program to count number of command line
argument, if no argument pass it should display following
output:
Program Name Is: ./a.out
No Extra Command Line Argument Passed Other Than
Program Name
Otherwise o/p should be :
admin1@admin1:~$ ./a.out deepali ahir
Program Name Is: ./a.out
Number Of Arguments Passed: 3
----Following Are The Command Line Arguments Passed----
argv[0]: ./a.out
argv[1]: deepali
argv[2]: ahir Prof. Deepali Ahir
#include<stdio.h>
int main(int argc,char* argv[])
{
int counter;
printf("Program Name Is: %s",argv[0]);
if(argc==1)
printf("\nNo Extra Command Line Argument Other Than Program
Name");
if(argc>=2)
{
printf("\nNumber Of Arguments Passed: %d",argc);
printf("\n----Following Are The Command Line Arguments
Passed----");
for(counter=0;counter<argc;counter++)
printf("\nargv[%d]: %s",counter,argv[counter]);
}
return 0; Prof. Deepali Ahir
}

If the input is :
admin1@admin1:~$ ./a.out "Deepali Ahir"

What will be the output?

Prof. Deepali Ahir


admin1@admin1:~$ g++ file.cpp
admin1@admin1:~$ ./a.out " Deepali Ahir"
Program Name Is: ./a.out
Number Of Arguments Passed: 2
----Following Are The Command Line Arguments
Passed----
argv[0]: ./a.out
argv[1]: Deepali Ahir

Prof. Deepali Ahir

You might also like