Sei sulla pagina 1di 38

File Management

• Most of the applications have their own


features to save some data to the local disk
and read data from the disk again.
• Files which are on the secondary storage
device are called physical files.
• In order to process file through program,
logical file must be created on the RAM.
• This logical file is nothing but an object having
ifstream, ofstream or fstream data type.
e.g. ifstream, ofstream
2/5/2019 1
Streams and Files
• The I/O system supplies a consistent interface to
the C++ programmer independent of the actual
device being accessed.
• This provides a level of abstraction between the
programmer and the device.
• This abstraction is called stream. The actual
device is called a file.
Streams example code
The C++ file system is designed to work with a wide
variety of devices, disk drives, and tape drives.
2/5/2019 2
continued
• Even though each device is very different, the
C++ file system transforms each into a logical
device called stream.
• Stream - a sequence of characters.

2/5/2019 3
continued
• You associate a stream with a specific file by
performing an open operation.
Infile.open(“hello.dat”,ios::in);
• Once a file is open, information can be
exchanged between it and a program.
• If the file can support position requests,
opening that file also initializes the file
position indicator to the start of the file.

2/5/2019 4
continued
• As each character is read from or written to
the file, the position indicator is incremented.
• You disassociate a file from a specific stream
with a close operation.
• If you close a file opened for output, then
contents, if any, of its associated stream are
written to the external device.
• this process is referred to as flushing the
stream.
• All files are closed automatically when the
program terminates normally.
2/5/2019 5
Classes for Stream I/O in C++
To perform file I/O, the header file fstream.h is
requied. fstream.h defines several classes,
including ifstream, ofstream, and fstream.
Three file I/O classes are used for File Read/Write
operations:
ifstream - Can be used for File read/input
operations
ofstream - Can be used for File write/output
operations
fstream - Can be used for both read/write c++
file I/O operations
2/5/2019 6
continued

• 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
2/5/2019 7
Types of files
•Your program can access files either in
sequential manner or random manner.
•The access mode of a file determines how one
can read, write, change, add and delete data
from a file.
-A sequential file has to be accessed in the same
order as the file was written.
-This is analogues to cassette tapes: you play
music in the same order as it was recorded.

2/5/2019 8
Types of files
•Unlike the sequential files, you can have
random-access to files in any order you want.
•Think of data in a random-access file as being
similar to songs on compact disc (CD):
you can go directly to any song you want to play
without having to play or fast-forward through the
other songs.

2/5/2019 9
Types of files
Sequential File Concepts
•- You can perform three operations on sequential
disk files.
•You can create disk files, add to disk files, and read
from disk files.
Opening and Closing Sequential Files
•- When you open a disk file, you only have to inform
C++, the file name and what you want to do with it.
•C++ and your operating system work together to
make sure that the disk is ready, and they create an
entry in your file directory for the filename (if you
are creating a file).
2/5/2019 10
Types of files
•When you close a file, C++ writes any remaining
data to the file, releases the file from the program,
and updates the file directory to reflect the file’s new
size.
• You can use either of the two methods to open a
file in C++:
o using a Constructor or
o using the open function
- The following C++ statement will create an object
with the name fout of ofstream class and this object
will be associated with file name “hello.txt”.
ofstream fout (“hello.txt”);
This statement uses the constructor method.
2/5/2019 11
Types of files
•- The following C++ statement will create an object
with the name fout of ofstream class and this object
will be associated with file name “hello.txt”.
ofstream fout;
fout.open(“hello.txt”);
•- If you open a file for writing (out access mode),
C++ creates the file.
•If a file by that name already exists, C++ overwrite
the old file with no warning.
•You must be careful when opening files not to
overwrite existing data that you want.
2/5/2019 12
Checking state flags

In addition to eof(), which checks if the end of file


has been reached, other member functions exist
to check the state of a stream (all of them return
a bool value):

2/5/2019 13
Types of files
•If an error occurs during opening of a file, C++ does
not create a valid file pointer (file object).
•Instead, C++ creates a file pointer (object) equal to
zero.
fstream myStream;
myStream.open ( "test", ios::in | ios::out );
If open ( ) fails, myStream will be zero
if (myStream){
cout << "Cannot open a file.\n";
// handle error
}
•For example if you open a file for output, but use an
invalid disk name, C++ can’t open the file and
therefore makes the file object equal to zero.
2/5/2019 14
2/5/2019 15
Types of files
•You can also determine the file access mode
when creating a file in C++.
•If you want to use the open function to open a
file then the syntax is:
fileobject.open(filename,accessmode);
•File name is a string containing a valid file name
for your computer.
• Accessmode is the sought operation to be taken
on the file and must be one of the values in the
following table.
2/5/2019 16
2/5/2019 17
Types of files
Writing to a sequential File
• The most common file I/O functions are
get() and put()
• You can also use the output redirection
operator (<<) to write to a file.
• - The following program creates a file called
names.txt in D:\ and saves the two lines of
text persons in it:

2/5/2019 18
Types of files
#include<fstream>
#include<cstdlib>
using namespce std;
ofstream fp;
Int main()

{
fp.open(“d:\\names.txt” ,ios::out);
if(fp.fail())
{
cerr<< “\nError opening file”;
getch();
exit(1);
}
fp<< “my team is out of the game”<<endl;
fp<< “I don’t like the tournament”<<endl;
fp.close();
}//end main

2/5/2019 19
Types of files
• Writing characters to sequential files:
• - A character can be written onto a file using the put() function. See the following code:
#include<fstream>
#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
char c;
ofstream outfile;
outfile.open(“D:\\test.txt”,ios::out);
if(outfile.fail())
{
cerr<< “\nError opening test.txt”;
exit(1);
}
for(int i=1;i<=15;i++)
{
cout<< “\nEnter a character : ”;
cin>>c;
outfile.put(c);
}
output.close();
}//end main

2/5/2019 20
Types of files
• The above program reads 4 characters and
stores in file test.txt.
• - You can easily add data to an existing file, or
create new files, by opening the file in
append access mode.
• - Files you open for append access mode
(using ios::app) do not have to exist. If the file
exists, C++ appends data to the end of the file
(as is done when you open a file for write
access).

2/5/2019 21
Reading and writing text files
Simply use the << and >> operators in the same
way you do when performing console I/O except
that instead of using cin and cout, you substitute
a stream that is linked to a file.
ofstream out;
out.open("inventory“, ios::out);
out <<"Radios" << 39.95 << endl;
out << "Toastors" << 19.95 << endl;
out.close ( );

2/5/2019 22
#include <fstream>
using namespace std;
int main()
{
ofstream outFile;
outFile.open(“EthioProgramming.txt");
outFile<<"Hello World!";
outFile.close();
return 0;
}

2/5/2019 23
continued
Example: Basic file operations
#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;
}
This code creates a file called example.txt and inserts a
sentence into it in the same way we are used to do with
cout, but using the file stream myfile instead.
2/5/2019 24
Example 2: writing on a text file
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile ("example.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; }
2/5/2019 25
Example 3: reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open()) {
while (! myfile.eof() ) {
getline (myfile,line);
cout << line << endl;
}
myfile.close(); }
else cout << "Unable to open file";
return 0; }
2/5/2019 26
This last example reads a text file and prints out
its content on the screen. Notice how we have
used a new member function, called eof() that
returns true in the case that the end of the file
has been reached. We have created a while loop
that finishes when indeed myfile.eof() becomes
true (i.e., the end of the file has been reached).

2/5/2019 27
get and put stream pointers
All I/O streams objects have, at least, one
internal stream pointer:
ifstream, like istream, has a pointer known as the
get pointer that points to the element to be read
in the next input operation.
•ofstream, like ostream, has a pointer known as
the put pointer that points to the location where
the next element has to be written.
•Finally, fstream, inherits both, the get and the
put pointers, from iostream (which is itself
derived from both istream and ostream).
2/5/2019 28
These internal stream pointers that point to the
reading or writing locations within a stream can
be manipulated using the following member
functions:
tellg() and tellp()
These two member functions have no
parameters and return a value of the member
type pos_type, which is an integer data type
representing the current position of the get
stream pointer (in the case of tellg) or the put
stream pointer (in the case of tellp).
2/5/2019 29
seekg() and seekp()
These functions allow us to change the position
of the get and put stream pointers. Both
functions are overloaded with two different
prototypes. The first prototype is:
seekg ( position );
seekp ( position );

2/5/2019 30
The other prototype for these functions is:
seekg ( offset, direction );
seekp ( offset, direction );
Using this prototype, the position of the get or
put pointer is set to an offset value relative to
some specific point determined by the parameter
direction.
offset is of the member type off_type, which is
also an integer type.
And direction is of type seekdir, which is an
enumerated type (enum) that determines the
point from where offset is counted from, and
that can take any of the following values:
2/5/2019 31
// position to the nth byte of fileObject (assumes
//ios::beg)
fileObject.seekg( n );
// position n bytes forward in fileObject
fileObject.seekg( n, ios::cur );
// position n bytes back from end of fileObject
fileObject.seekg( n, ios::end );
// position at end of fileObject
fileObject.seekg( 0, ios::end );

2/5/2019 32
2/5/2019 33
The following example uses the member functions we
have just seen to obtain the size of a file:
Example: obtaining file size
#include <iostream>
#include <fstream>
using namespace std;
int main () {
long begin,end;
ifstream myfile ("example.txt");
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
cout << "size is: " << (end-begin) << " bytes.\n"; return 0;}

2/5/2019 34
Random Access File
• Random access enables you to read or write any
data in your disk file with out having to read and
write every piece of data that precedes it.
• Generally you read and write file records.
• A record to a file is analogues to a C++ structure.
• A record is a collection of one or more data
values (called fields) that you read and write to
disk.
• Generally you store data in the structures and
write structures to disk.
• -

2/5/2019 35
Random Access File
• When you read a record from disk, you
generally read that record into a structure
variable and process it with your program.
• - Most random access files are fixed-length
records. Each record (a row in the file) takes
the same amount of disk space.
• -With fixed length records, your computer can
better calculate where on the disk the desired
record is located.

2/5/2019 36
Opening Random-Access Files
• There is really no difference between sequential
files and random files in C++. The difference
between the files is not physical, but lies in the
method that you use to access them and update
them.
• The ostream member function write outputs a
fixed number of bytes, beginning at a specific
location in memory, to the specified stream.
• When the stream is associated with a file,
function write writes the data at the location in
specified by the “put” file position pointer.

2/5/2019 37
Opening Random-Access Files
• The istream member function read inputs a fixed
number of bytes from the specified stream into an
area in memory beginning at the specified address.
• When the stream is associated with a file, function
read inputs bytes at the location in the file specified
by the “get” file position pointer.
• Syntax of write:
fileobject.write((char*) & NameOfObject, sizeof(name of object))
• Function write expects data type const char* as its
first argument. The second argument of write is an
integer of type size specifying the number of bytes
to be written.

2/5/2019 38

Potrebbero piacerti anche