Association of stream buffers with files for file reading and writing.
The sections in this chapter are:
The header <fstream> defines template classes and types to assist in reading and writing of files.
Prototype:
namespace std{
template
<class charT,class traits = ios_traits<charT> >
class basic_filebuf;
typedef basic_filebuf<char> filebuf;
typedef basic_filebuf<wchar_t> wfilebuf;
template
<class charT, class traits = ios_traits<charT> >
class basic_ifstream;
typedef basic_ifstream<char> ifstream;
typedef basic_ifstream<wchar_t> wifstream;
template
<class charT, class traits = ios_traits<charT> >
class basic_ofstream;
typedef basic_ofstream<char> ofstream;
typedef basic_ofstream<wchar_t> wofstream;
}
AFILE refers to the type FILE as defined in the Standard C Library and provides an external input or output stream with the underlying
type of char or byte. A stream is a sequence of char or bytes.
A class to provide for input and output file stream buffering mechanisms.
The prototype is listed below. Other topics in this section are:
namespace std{
template
<class charT, class traits = ios_traits<charT> >
class basic_filebuf : public basic_streambuf <charT, traits>
{
public:
typedef charT char_type;
typedef typename traits::int_type int_type;
typedef typename traits::pos_type pos_type;
typedef typename traits::off_type off_type;
basic_filebuf();
virtual ~basic_filebuf();
bool is_open() const;
basic_filebuf<charT, traits>* open
(const char* c, ios_base::openmode mode);
basic_filebuf<charT, traits>* close();
protected:
virtual int showmanyc();
virtual int_type underflow();
virtual int_type pbackfail
(int_type c = traits::eof());
virtual int_type overflow
(int_type c = traits::eof());
virtual basic_streambuf<charT traits>* setbuf
(char_type* s, streamsize n);
virtual pos_type seekoff
(off_type off,
ios_base::seekdir way,
ios_base::in | ios_base::out);
virtual pos_type seekpos
(pos_type sp,
ios_base::openmode which,
ios_base::in | ios_base::out);
virtual int sync();
virtual void imbue(const locale& loc);
};
}
The filebuf class is derived from the streambuf class and provides a buffer
for file output and or input.
To construct and initialize a filebuf object.
Prototype:
basic_filebuf()Remarks:
The constructor opens a basic_filebuf object and initializes it with basic_streambuf<charT, traits>() and if successful is_open() is false.
To remove the basic_filebuf object from memory.
Prototype:
virtual ~basic_filebuf();For example of basic_filebuf::basic_filebuf() usage::
The file MW Reference before operation contains. Metrowerks CodeWarrior "Software at Work"
#include <iostream> #include <fstream> #include <cstdio> #include <cstring> char inFile[ ] = "MW Reference"; int main() { using namespace std; FILE *fp = fopen( inFile, "a+"); filebuf in(fp); if( !in.is_open() ) { cout << "could not open file"; exit(1); } char str[] = "\n\ttrademark"; in.sputn(str, strlen(str)); in.close(); return 0; }
Result: The file MW Reference now contains: Metrowerks CodeWarrior "Software at Work" trademark
27.8.1.3 Member functions
basic_filebuf::is_open
Test to ensure
filebufstream is open for reading or writing.
Prototype:
bool is_open() constRemarks:
Use the function
is_open() for a filebuf stream to ensure it is open before attemptingto do any input or output operation on the stream.
Return:
True if stream is available and open.
For example of basic_filebuf::is_open() usage:
See: basic_filebuf::basic_filebuf
basic_filebuf::open
Open a
basic_filebufobject and associate it with a file.
Prototype:
basic_filebuf<charT, traits>* open
(const char* c,
ios_base::openmode mode);Remarks:
You would use the function
open() to open a filebuf object and associate it with a file. Youmay use
open() to reopen a buffer and associate it if the object was closedbut not destroyed.
WARNING!
If an attempt is made to open a file in an inappropriate file
opening mode, the file will not open and a test for the object
will not give false, therefore use the function
is_open() to check for file openings.
Legal basic_filebuf file opening modes:
|
Opening Modes
|
stdio equivalent
|
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Return:
If successful the this pointer is returned, if is_open() equals true then a null pointer is returned.
Example of filebuf::open() usage::
The file MW Reference before operation contained: Metrowerks CodeWarrior "Software at Work"
#include <fstream> #include <cstdlib> char inFile[] = "MW Reference"; int main(){ using namespace std; filebuf in; in.open(inFile, ios::out | ios::app); if(!in.is_open()) {cout << "could not open file"; exit(1);} char str[] = "\n\tregistered trademark"; in.sputn(str, strlen(str)); in.close(); return 0; }
Result: The file MW Reference now contains: Metrowerks CodeWarrior "Software at Work" registered trademark
basic_filebuf::close
To close a
filebufstream without destroying it.
Prototype:
basic_filebuf<charT, traits>* close();Remarks:
The function close() would remove the stream from memory but
will not remove the filebuf object. You may re-open a filebuf
stream that was closed using the close() function.
Return:
The
this pointerwith success otherwise anull pointer.
For example of basic_filebuf::close() usage:
See basic_filebuf::open()
27.8.1.4 Overridden virtual functions
basic_filebuf::showmanyc
Overrides basic_streambuf::showmanyc().
Prototype:
virtual int showmanyc();Remarks:
Behaves the same as basic_sreambuf::showmanyc().
basic_filebuf::underflow
Overrides basic_streambu::underflow();
Prototype:
virtual int_type underflow();Remarks:
Behaves the same as basic_streambuf::underflow with the specialization
that a sequence of characters is read as if they were read from
a file into an internal buffer.
basic_filebuf::pbackfail
Overrides basic_streambuf::pbackfail().
Prototype:
virtual int_type pbackfail
(int_type c = traits::eof());Remarks :
This function puts back the characters designated by
cto the input sequence if possible.
Return:
traits::eof()if failure and returns either the character put back ortraits::not_eof(c)for success.
basic_filebuf::overflow
Overrides basic_streambuf::overflow()
Prototype:
virtual int_type overflow
(int_type c = traits::eof());Remarks:
Behaves the same as basic_strreambuf<charT, traits>::overflow(c)
except the behavior of consuming characters is performed by conversion.
Return:
basic_filebuf::seekoff
Overrides basic_streambuf::seekoff()
Prototype:
virtual pos_type seekoff
(off_type off,
ios_base::seekdir way,
ios_base::in | ios_base::out);Remarks:
Sets the offset position of the stream as if using the C standard
library function
fseek(file, off, whence).
Return:
Seekoff function returns a newly formed
pos_typeobject which contains all information needed to determine thecurrent position if successful. An invalid stream position if
it fails.
basic_filebuf::seekpos
Overrides basic_streambuf::seekpos()
Prototype:
virtual pos_type seekpos
(pos_type sp,
ios_base::openmode which,
ios_base::in | ios_base::out);Remarks:
Description undefined in standard at the time of writing.
Return:
Seekpos function returns a newly formed
pos_typeobject which contains all information needed to determine thecurrent position if successful. An invalid stream position if
it fails.
basic_filebuf::setbuf
Overrides basic_streambuf::setbuf()
Prototype:
virtual basic_streambuf<charT traits>* setbuf
(char_type* s, streamsize n);Remarks:
Description undefined in standard at the time of writing.
basic_filebuf::sync
Overrides basic_streambuf::sync
Prototype:
virtual int sync();Remarks:
Description undefined in standard at the time of writing.
basic_filebuf::imbue
Overrides basic_streambuf::imbue
Prototype:
virtual void imbue(const locale& loc);Remarks:
Description undefined in standard at the time of writing.
27.8.1.5 Template class basic_ifstream
A class to provide for input file stream mechanisms.
The prototype is listed below. Other topics in this section are:
namespace std{
template
<class charT, class traits = ios_traits<charT> > {
class basic_ifstream : public basic_istream<charT, traits>
{
public:
typedef charT char_type;
typedef typename traits:int_type int_type;
typedef typename traits:pos_type pos_type;
typedef typename traits:off_type off_type;
basic_ifstream();
explicit basic_ifstream
(const char *s, openmode mode = in);
basic_filebuf<charT, traits>* rdbuf() const;
bool is_open();
void open(const char* s, openmode mode = in);
void close();
private:
basic_filebuf<charT, traits> sb; exposition only };
}
NOTE
If the basic_ifstream supports reading from file. It uses a basic_filebuf
object to control the sequence. That object is represented here
as basic_filebuf sb.
The basic_ifstream provides mechanisms specifically for input
file streams.
Create a file stream for input.
Prototype:
basic_ifstream();
explicit basic_ifstream
(const char *s, openmode mode = in);
Remarks:
The constructor creates a stream for file input; it is overloaded
to either create and initialize when called or to simply create
a class and be opened using the open() member function.he default opening mode is ios::in.see basic_filebuf::open() for valid open mode settings.
NOTE
See basic_ifstream::open for legal opening modes.
basic_ifstream::open() for overloaded form usage.
Example of basic_ifstream::basic_ifstream() constructor usage:
:
The MW Reference file contains: Metrowerks CodeWarrior "Software at Work"
#include <iostream> #include <fstream> #include <cstdlib> char inFile[] = "MW Reference"; int main() { using namespace std; ifstream in(inFile, ios::in); if(!in.is_open()) {cout << "can't open input file"; exit(1);} char c ='\0'; while(in.good()) { if(c) cout << c; in.get(c); } in.close(); return 0; }
Result: Metrowerks CodeWarrior "Software at Work"
27.8.1.7 Member functions
basic_ifstream::rdbuf
Th
e rdbuf()function retrieves a pointer to afilebuftype buffer.
Prototype:
basic_filebuf<charT, traits>* rdbuf() const;Remarks:
In order to manipulate for random access or use an
ifstreamstream for both input and output you need to manipulate the basebuffer. The function
rdbuf() returns a pointer to this buffer for manipulation.
Return:
A pointer to type
basic_filebuf.
Example of basic_ifstream::rdbuf() usage::
The MW Reference file contains originally Metrowerks CodeWarrior "Software at Work"
#include <iostream> #include <fstream> #include <cstdlib> char inFile[] = "MW Reference"; int main() { using namespace std; ifstream inOut(inFile, ios::in | ios::out); if(!inOut.is_open()) {cout << "Could not open file"; exit(1);} ostream Out(inOut.rdbuf()); char str[] = "\n\tRegistered Trademark"; inOut.rdbuf()->pubseekoff(0, ios::end); Out << str; inOut.close(); return 0; }
Result: The File now reads: Metrowerks CodeWarrior "Software at Work" Registered Trademark
basic_ifstream::is_open
Prototype:
bool is_open() constRemarks:
Use
is_open() to test that a stream is indeed open and ready for input fromthe file.
Return:
For example of basic_ifstream::is_open() usage :
See basic_ifstream::basic_ifstream()
basic_ifstream::open
Open is used to open a file or reopen a file after closing it.
Prototype:
void open(const char* s, openmode mode = in);Remarks:
The default open mode is
ios::in, but can be one of several modes. (see below) A stream is openedand prepared for input or output as selected.
Return:
17.4.1.1.4 Legal basic_ifstream file opening modes:
|
Opening Modes
|
stdio equivalent
|
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
NOTE
If an attempt is made to open a file in an inappropriate file
opening mode, the file will not open and a test for the object
will not give false, therefore use the function is_open() to check for file openings
The MW Reference file contains: Metrowerks CodeWarrior "Software at Work"
#include <iostream> #include <fstream> #include <cstdlib> char inFile[] = "MW Reference"; int main() { using namespace std; ifstream in; in.open(inFile); if(!in.is_open()) {cout << "can't open input file"; exit(1);} char c = NULL; while((c = in.get()) != EOF) { cout << c; } in.close(); return 0; }
Result: Metrowerks CodeWarrior "Software at Work"
basic_ifstream::close
Prototype:
void close();Remarks:
The
close() function closes the stream for operation but does not destroythe ifstream object so it may be re-opened at a later time. If
the function fails calls setstate(failbit) which may throw and
exception.
Return::
Example of basic_ifstream::close() usage::
See basic_ifstream::basic_ifstream()
27.8.1.8 Template class basic_ofstream
A class to provide for output file stream mechanisms.
The prototype is listed below. Other topics in this section are:
namespace std{
template
<class charT, class traits = ios_traits<charT> >
class basic_ofstream : public basic_ostream<charT, traits>
{
public:
typedef charT char_type;
typedef typename traits:int_type int_type;
typedef typename traits:pos_type pos_type;
typedef typename traits:off_type off_type;
basic_ofstream();
explicit basic_ofstream
(const char *s, openmode mode = out | trunc);
basic_filebuf<charT, traits>* rdbuf() const;
bool is_open();
void open(const char* s, openmode mode = out);
void close();
private:
basic_filebuf<charT, traits> sb; exposition only };
}
NOTE
The basic_ofstream supports writing to file. It uses a basic_filebuf
object to control the sequence. That object is represented here
as basic_filebuf sb.
The basic_ofstream class provides for mechanisms specific to output file streams.
To create a file stream object for output.
Prototype:
basic_ofstream();
explicit basic_ofstream
(const char *s, openmode mode = out | trunc);
Remarks:
The class basic_ofstream creates an object for handling file output. It may be opened
later using the ofstream:: open() member function. It may also be associated with a file when
the object is declared. The default open mode is ios::out.
NOTE
There are only certain valid file opening modes for an ofstream
object see basic_ofstream::open() for a list of valid opening modes.
Before the operation the file MW Reference may or may not exist.
#include <iostream> #include <fstream> #include <cstdlib> char outFile[] = "MW Reference"; int main() { using namespace std; ofstream out(outFile); if(!out.is_open()) {cout << "file not opened"; exit(1);} out << "This is an annotated reference that " << "contains a description\n" << "of the Working ANSI C++ Standard " << "Library and other\nfacilities of " << "the Metrowerks Standard Library. "; out.close(); return 0; }
Result: This is an annotated reference that contains a description of the Working ANSI C++ Standard Library and other facilities of the Metrowerks Standard Library.
27.8.1.10 Member functions
basic_ofstream::rdbuf
To retrieve a pointer to the stream buffer.
Prototype:
basic_filebuf<charT, traits>* rdbuf() const;Remarks:
In order to manipulate a stream for random access or other operations
you must use the streams base buffer. The member function rdbuf()
is used to return a pointer to this buffer.
Return:
Example of basic_ofstream::rdbuf() usage::
The file MW Reference before the operation contains: This is an annotated reference that contains a description of the Working ANSI C++ Standard Library and other facilities of the Metrowerks Standard Library
#include <iostream> #include <fstream> #include <cstdlib> char outFile[] = "MW Reference"; int main() { using namespace std; ofstream out(outFile, ios::in | ios::out); if(!out.is_open()) {cout << "could not open file for output"; exit(1);} istream inOut(out.rdbuf()); char ch; while((ch = inOut.get()) != EOF) { cout.put(ch); } out << "\nAnd so it goes..."; out.close(); return 0; }
Result: This is an annotated reference that contains a description of the Working ANSI C++ Standard Library and other facilities of the Metrowerks Standard Library. This is an annotated reference that contains a description of the Working ANSI C++ Standard Library and other facilities of the Metrowerks Standard Library. And so it goes...
basic_ofstream::is_open
To test whether the file was opened.
Prototype:
bool is_open();Remarks:
The
is_open() function is used to check that a file stream was indeed openedand ready for output. You should always test with this function
after using the constructor or the
open() function to open a stream.
Return:
Trueif file stream is open and available for output.
For example of basic_ofstream::is_open() usage :
See basic_ofstream::ofstream()
basic_ofstream::open
To open or re-open a file stream for output.
Prototype:
void open(const char* s, openmode mode = out);Remarks:
The function
open() opens a file stream for output. The default mode isios::out, but may be any valid open mode (see below.) If failure occurs
open()callssetstate(failbit)which may throw an exception.
Return:
Legal basic_ofstream file opening modes.:
|
Opening Modes
|
stdio equivalent
|
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
NOTE
If an attempt is made to open a file in an inappropriate file
opening mode, the file will not open and a test for the object
will not give false, therefore use the function is_open() to check for file openings.
Before operation, the file MW Reference contained: Chapter One
#include <iostream> #include <fstream> #include <cstdlib> char outFile[] = "MW Reference"; int main() { using namespace std; ofstream out; out.open(outFile, ios::out | ios::app); if(!out.is_open()) {cout << "file not opened"; exit(1);} out << "\nThis is an annotated reference that " << "contains a description\n" << "of the Working ANSI C++ Standard " << "Library and other\nfacilities of " << "the Metrowerks Standard Library."; out.close(); return 0; }
Result: After the operation MW Reference contained Chapter One This is an annotated reference that contains a description of the Working ANSI C++ Standard Library and other facilities of the Metrowerks Standard Library.
basic_ofstream::close
The member function closes the stream but does not destroy it.
Prototype:
void close();Remarks:
Use the function
close()to close a stream. It may be re-opened at a later time usingthe member function
open(). If failure occursopen()callssetstate(failbit)which may throw an exception.
Return:
For example of basic_ofstream::close() usage.:
basic_ofstream()
27.8.1.11 Template class basic_fstream
A template class for the association of a file for input and
output
The prototype is listed below. The other topic in this section
is:
namespace std {
template
<class charT, class traits=ios_traits<charT> >
class basic_fstream : public basic_iostream<charT, traits>
{
public:
typedef charT char_type;
typedef typename traits::int_type int_type;
typedef typename traits::pos_type pos_type;
typedef typename traits::off_type off_type;
basic_fstream();
explicit basic_fstream
(const char *s,
ios_base::openmode = ios_base::in | ios_base::out);
basic_filebuf<charT, traits>* rdbuf() const;
bool is_open();
void open
(const char* s,
ios_base::openmode = ios_base::in | ios_base::out);
void close();
private:
basic_filebuf<charT, traits> sb; exposition only };
}
The template class basic_fstream is used for both reading and
writing from files.
NOTE
The basic_fstream supports writing to file. It uses a basic_filebuf
object to control the sequence. That object is represented here
as basic_filebuf sb.
To construct an object of basic_ifstream for input and output
operations.
Prototypes:
basic_fstream();
explicit basic_fstream
(const char *s,
ios_base::openmode =
ios_base::in | ios_base::out);
Remarks:
The basic_fstream class is derived from basic_iostream and that and a basic_filebuf object are initialized at construction.
Example of basic_fstream:: basic_fstream() usage:
The MW Reference file contains originally Metrowerks CodeWarrior "Software at Work"
#include <iostream> #include <fstream> #include <cstdlib> char inFile[] = "MW Reference"; int main() { using namespace std; fstream inOut(inFile, ios::in | ios::out); if(!inOut.is_open()) {cout << "Could not open file"; exit(1);} char str[] = "\n\tRegistered Trademark"; char ch; while((ch = inOut.get())!= EOF) { cout << ch; } inOut.clear(); inOut << str; inOut.close(); return 0; }
Result: Metrowerks CodeWarrior "Software at Work" The File now reads: Metrowerks CodeWarrior "Software at Work" Registered Trademark
27.8.1.13 Member Functions
basic_fstream::rdbuf
Th
e rdbuf()function retrieves a pointer to afilebuftype buffer.
Prototype:
basic_filebuf<charT, traits>* rdbuf() const;Remarks:
In order to manipulate for random access or use of an
fstreamstream you may need to manipulate the base buffer. The function
rdbuf() returns a pointer to this buffer for manipulation.
Return:
A pointer to type
basic_filebuf.
Example of basic_fstream::rdbuf() usage:
The MW Reference file contains originally Metrowerks CodeWarrior "Software at Work"
#include <iostream> #include <fstream> #include <cstdlib> char inFile[] = "MW Reference"; int main() { using namespace std; fstream inOut; inOut.open(inFile, ios::in | ios::out); if(!inOut.is_open()) {cout << "Could not open file"; exit(1);} char str[] = "\n\tRegistered Trademark"; inOut.rdbuf()->pubseekoff(0,ios::end); inOut << str; inOut.close(); return 0; }
Result: The File now reads: Metrowerks CodeWarrior "Software at Work" Registered Trademark
basic_fstream::is_open
Test to ensure
basic_fstreamfile is open and available for reading or writing.
Prototype:
bool is_open() constRemarks:
Use the function
is_open() for abasic_fstreamfile to ensure it is open before attempting to do any input oroutput operation on a file.
Return:
True if a file is available and open.
For an example, see "Example of basic_fstream:: basic_fstream() usage".
basic_fstream::open
To open or re-open a file stream for input or output.
Prototypes:
void open
(const char* s,
ios_base::openmode =
ios_base::in | ios_base::out);Remarks:
You would use the function
open() to open a basic_fstream object and associate it with a file.You may use
open() to reopen a file and associate it if the object was closedbut not destroyed.
WARNING!
If an attempt is made to open a file in an inappropriate file
opening mode, the file will not open and a test for the object
will not give false, therefore use the function
is_open() to check for file openings.
Legal file opening modes:
|
Opening Modes
|
stdio equivalent
|
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Return:
For an example, see "Example of basic_fstream::rdbuf() usage".
The member function closes the stream but does not destroy it.
Prototype:
void close();
Remarks:
Use the function close() to close a stream. It may be re-opened at a later time using
the member function open(). If failure occurs open() calls setstate(failbit) which may throw an exception.
Return:
For an example, see "Example of basic_fstream:: basic_fstream() usage".
Visit the Metrowerks website at: http://www.metrowerks.com
For assistance contact Metrowerks Technical Support at: cw_support@metrowerks.com
Copyright © 2000, Metrowerks Corp. All rights reserved.
Last updated: July 21, 2000