basic_filebuf::open

Open a basic_filebuf object and associate it with a file.

  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. You may use open() to reopen a buffer and associate it if the object was closed but not destroyed.

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.

If successful the this pointer is returned, if is_open() equals true then a null pointer is returned.

Table 1. Legal basic_filebuf file opening modes
Opening Modes stdio equivalent
Input Only  
ios:: in "r"
ios:: binary | ios::in "rb"
Output only  
ios::out "w"
ios::binary | ios::out "wb"
ios::out | ios::trunc "w"
ios::binary | ios::out | ios::trunc "wb"
ios::out | ios::app "a"
Input and Output  
ios::in | ios::out "r+"
ios::binary | ios::in | ios::out "r+b"
ios:: in | ios::out | ios::trunc "w+"
ios::binary | ios::in | ios::out | ios::trunc "w+b"
ios::binary | ios:: out | ios::app "ab"
Listing: Example of filebuf::open() usage:
// The file ewl-test before operation contained:
// CodeWarrior "Software at Work"

#include <fstream>
#include <cstdlib>

char inFile[] = "ewl-test";

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 ewl-test now contains:
  CodeWarrior "Software at Work"
  registered trademark