Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/io/basic ofstream"

From cppreference.com
< cpp‎ | io
(Added example)
m (headers sorted)
 
(9 intermediate revisions by 6 users not shown)
Line 1: Line 1:
 
{{cpp/title|basic_ofstream}}
 
{{cpp/title|basic_ofstream}}
 
{{cpp/io/basic_ofstream/navbar}}
 
{{cpp/io/basic_ofstream/navbar}}
{{ddcl | header=fstream |
+
{{ddcl|header=fstream|1=
template<  
+
template<
     class CharT,  
+
     class CharT,
     class Traits {{=}} std::char_traits<CharT>
+
     class Traits = std::char_traits<CharT>
 
> class basic_ofstream : public std::basic_ostream<CharT, Traits>
 
> class basic_ofstream : public std::basic_ostream<CharT, Traits>
 
}}
 
}}
Line 10: Line 10:
 
The class template {{tt|basic_ofstream}} implements high-level output operations on file based streams. It interfaces a file-based streambuffer ({{lc|std::basic_filebuf}}) with the high-level interface of ({{lc|std::basic_ostream}}).
 
The class template {{tt|basic_ofstream}} implements high-level output operations on file based streams. It interfaces a file-based streambuffer ({{lc|std::basic_filebuf}}) with the high-level interface of ({{lc|std::basic_ostream}}).
  
A typical implementation of {{tt|std::basic_ofstream}} holds only one non-derived data member: an instance of {{c|std::basic_filebuf<CharT, Traits>}}.
+
A typical implementation of {{tt|std::basic_ofstream}} holds only one non-derived data member: an instance of {{c/core|std::basic_filebuf<CharT, Traits>}}.
  
 
{{inheritance diagram/std-basic_ofstream}}
 
{{inheritance diagram/std-basic_ofstream}}
  
Two specializations for common character types are also defined:
+
{{cpp/basic char typedefs|ofstream|fstream}}
  
{{dsc begin}}
+
{{cpp/io/member types|ofstream}}
{{dsc header | fstream}}
+
{{dsc hitem | Type | Definition}}
+
{{dsc | {{tt|ofstream}} | {{c|basic_ofstream<char>}}}}
+
{{dsc | {{tt|wofstream}} | {{c|basic_ofstream<wchar_t>}}}}
+
{{dsc end}}
+
 
+
===Member types===
+
{{dsc begin}}
+
{{dsc hitem | Member type | Definition}}
+
{{dsc inc | cpp/io/dsc char_type}}
+
{{dsc inc | cpp/io/dsc traits_type}}
+
{{dsc inc | cpp/io/dsc int_type}}
+
{{dsc inc | cpp/io/dsc pos_type}}
+
{{dsc inc | cpp/io/dsc off_type}}
+
{{dsc end}}
+
  
 
===Member functions===
 
===Member functions===
 
{{dsc begin}}
 
{{dsc begin}}
{{dsc inc | cpp/io/basic_fstream/dsc constructor | basic_ofstream}}
+
{{dsc inc|cpp/io/basic_fstream/dsc constructor|basic_ofstream}}
{{dsc inc | cpp/io/basic_fstream/dsc destructor | basic_ofstream}}
+
{{dsc inc|cpp/io/basic_fstream/dsc destructor|basic_ofstream}}
{{dsc inc | cpp/io/basic_fstream/dsc operator{{=}} | basic_ofstream}}
+
{{dsc inc|cpp/io/basic_fstream/dsc operator{{=}}|basic_ofstream}}
{{dsc inc | cpp/io/basic_fstream/dsc swap | basic_ofstream}}
+
{{dsc inc|cpp/io/basic_fstream/dsc swap|basic_ofstream}}
{{dsc inc | cpp/io/basic_fstream/dsc rdbuf | basic_ofstream}}
+
{{dsc inc|cpp/io/basic_fstream/dsc rdbuf|basic_ofstream}}
 +
{{dsc inc|cpp/io/basic_ofstream/dsc native_handle}}
  
{{dsc h2 | File operations }}
+
{{dsc h2|File operations}}
{{dsc inc | cpp/io/basic_fstream/dsc is_open | basic_ofstream}}
+
{{dsc inc|cpp/io/basic_fstream/dsc is_open|basic_ofstream}}
{{dsc inc | cpp/io/basic_fstream/dsc open | basic_ofstream}}
+
{{dsc inc|cpp/io/basic_fstream/dsc open|basic_ofstream}}
{{dsc inc | cpp/io/basic_fstream/dsc close | basic_ofstream}}
+
{{dsc inc|cpp/io/basic_fstream/dsc close|basic_ofstream}}
 
{{dsc end}}
 
{{dsc end}}
  
 
===Non-member functions===
 
===Non-member functions===
 
{{dsc begin}}
 
{{dsc begin}}
{{dsc inc | cpp/io/basic_fstream/dsc swap2 | basic_ofstream}}
+
{{dsc inc|cpp/io/basic_fstream/dsc swap2|basic_ofstream}}
 
{{dsc end}}
 
{{dsc end}}
 
  
 
{{cpp/io/basic_ostream/inherit}}
 
{{cpp/io/basic_ostream/inherit}}
 
{{cpp/io/basic_ios/inherit}}
 
{{cpp/io/basic_ios/inherit}}
 
{{cpp/io/ios_base/inherit}}
 
{{cpp/io/ios_base/inherit}}
 +
 +
===Notes===
 +
{{feature test macro|__cpp_lib_fstream_native_handle|std=C++26|value=202306L|native handles support}}
  
 
===Example===
 
===Example===
 
{{example
 
{{example
 
|code=
 
|code=
#include <iostream>
 
 
#include <fstream>
 
#include <fstream>
#include <limits>
+
#include <iostream>
 
#include <string>
 
#include <string>
  
struct Birthday { long day, month, year; };
+
int main()
 
+
{
class Entry {
+
    std::string name;
+
    Birthday bday;
+
public:
+
    Entry(std::string name_, long day_, long month_, long year_) :
+
        name(name_), bday({day_, month_, year_}) {}
+
    void printToStdOut() {
+
        std::cout << name << ' ' << bday.day << '/' << bday.month << '/'
+
                  << bday.year << '\n';
+
    }
+
    //name and bday are private so we must make << and >> friends of the class or
+
    // otherwise write getter and setter methods for name and bday
+
    friend std::ostream &operator<<(std::ostream &, Entry &);
+
    friend std::istream &operator>>(std::istream &, Entry &);
+
};
+
 
+
std::ostream &operator<<(std::ostream &strm, Entry &e) {
+
    //Since the length of e.name is not necessarily known at compile time, we
+
    // can't simply use: strm.write(reinterpret_cast<char*>(&e), sizeof e);
+
    unsigned int length = e.name.length();
+
    strm.write(reinterpret_cast<char*>(&length), sizeof length);
+
    strm.write(&e.name[0], length);
+
    strm.write(reinterpret_cast<char*>(&e.bday), sizeof e.bday);
+
    return strm;
+
}
+
 
+
std::istream &operator>>(std::istream &strm, Entry &e) {
+
    unsigned int length;
+
    strm.read(reinterpret_cast<char*>(&length), sizeof length);
+
    e.name.resize(length);
+
    strm.read(&e.name[0], length);
+
    strm.read(reinterpret_cast<char*>(&e.bday), sizeof e.bday);
+
    return strm;
+
}
+
 
+
int main() {
+
    Entry e("Alpha", 1, 1, -13820000000);
+
    e.printToStdOut();
+
   
+
 
     std::string filename = "Test.b";
 
     std::string filename = "Test.b";
     std::ofstream ostrm;
+
     {
    //Open the file or else create it
+
        std::ofstream ostrm(filename, std::ios::binary);
    ostrm.open(filename, std::fstream::binary);
+
         double d = 3.14;
    if(!ostrm.is_open()) {
+
         ostrm.write(reinterpret_cast<char*>(&d), sizeof d); // binary output
         ostrm.clear();
+
         ostrm << 123 << "abc" << '\n';                     // text output
         ostrm.open(filename, std::fstream::out); //Create the file
+
        ostrm.close();
+
        ostrm.open(filename, std::fstream::binary);
+
         if(!ostrm.good())
+
            return 1;
+
 
     }
 
     }
 
      
 
      
     //write the Entry e to the file
+
     // read back
    ostrm << e;
+
     std::ifstream istrm(filename, std::ios::binary);
    ostrm.close();
+
     double d;
   
+
    istrm.read(reinterpret_cast<char*>(&d), sizeof d);
    Entry e_recovered("Omega", 31, 12, std::numeric_limits<long>::max());
+
    int n;
    e_recovered.printToStdOut();
+
     std::string s;
 
+
     istrm >> n >> s;
    //Open the file for reading
+
     std::cout << " read back: " << d << ' ' << n << ' ' << s << '\n';
     std::ifstream istrm;
+
    istrm.open(filename, std::fstream::binary);
+
     if(!istrm.good())
+
        return 1;
+
 
+
     //overwrite e_recovered with the values from istrm
+
     istrm >> e_recovered;
+
     istrm.close();
+
   
+
    e_recovered.printToStdOut();
+
    return 0;
+
 
}
 
}
 
|output=
 
|output=
Alpha 1/1/-13820000000
+
read back: 3.14 123 abc
Omega 31/12/9223372036854775807
+
Alpha 1/1/-13820000000
+
 
}}
 
}}
  
 
+
{{langlinks|de|es|fr|it|ja|pt|ru|zh}}
[[de:cpp/io/basic ofstream]]
+
[[es:cpp/io/basic ofstream]]
+
[[fr:cpp/io/basic ofstream]]
+
[[it:cpp/io/basic ofstream]]
+
[[ja:cpp/io/basic ofstream]]
+
[[pt:cpp/io/basic ofstream]]
+
[[ru:cpp/io/basic ofstream]]
+
[[zh:cpp/io/basic ofstream]]
+

Latest revision as of 08:36, 9 September 2023

 
 
 
 
Defined in header <fstream>
template<

    class CharT,
    class Traits = std::char_traits<CharT>

> class basic_ofstream : public std::basic_ostream<CharT, Traits>

The class template basic_ofstream implements high-level output operations on file based streams. It interfaces a file-based streambuffer (std::basic_filebuf) with the high-level interface of (std::basic_ostream).

A typical implementation of std::basic_ofstream holds only one non-derived data member: an instance of std::basic_filebuf<CharT, Traits>.

cpp/io/ios basecpp/io/basic ioscpp/io/basic ostreamstd-basic ofstream-inheritance.svg

Inheritance diagram

Several typedefs for common character types are provided:

Defined in header <fstream>
Type Definition
std::ofstream std::basic_ofstream<char>
std::wofstream std::basic_ofstream<wchar_t>

Contents

[edit] Member types

Member type Definition
char_type CharT[edit]
traits_type Traits; the program is ill-formed if Traits::char_type is not CharT.[edit]
int_type Traits::int_type[edit]
pos_type Traits::pos_type[edit]
off_type Traits::off_type[edit]
native_handle_type(C++26) implementation-defined type that is TriviallyCopyable and semiregular[edit]

[edit] Member functions

constructs the file stream
(public member function) [edit]
(destructor)
[virtual] (implicitly declared)
destructs the basic_ofstream and the associated buffer, closes the file
(virtual public member function) [edit]
(C++11)
moves the file stream
(public member function) [edit]
(C++11)
swaps two file streams
(public member function) [edit]
returns the underlying raw file device object
(public member function) [edit]
returns the underlying implementation-defined handle
(public member function) [edit]
File operations
checks if the stream has an associated file
(public member function) [edit]
opens a file and associates it with the stream
(public member function) [edit]
closes the associated file
(public member function) [edit]

[edit] Non-member functions

specializes the std::swap algorithm
(function template) [edit]

Inherited from std::basic_ostream

Member functions

Formatted output
inserts formatted data
(public member function of std::basic_ostream<CharT,Traits>) [edit]
Unformatted output
inserts a character
(public member function of std::basic_ostream<CharT,Traits>) [edit]
inserts blocks of characters
(public member function of std::basic_ostream<CharT,Traits>) [edit]
Positioning
returns the output position indicator
(public member function of std::basic_ostream<CharT,Traits>) [edit]
sets the output position indicator
(public member function of std::basic_ostream<CharT,Traits>) [edit]
Miscellaneous
synchronizes with the underlying storage device
(public member function of std::basic_ostream<CharT,Traits>) [edit]

Member classes

implements basic logic for preparation of the stream for output operations
(public member class of std::basic_ostream<CharT,Traits>) [edit]

Inherited from std::basic_ios

Member types

Member type Definition
char_type CharT
traits_type Traits
int_type Traits::int_type
pos_type Traits::pos_type
off_type Traits::off_type

Member functions

State functions
checks if no error has occurred i.e. I/O operations are available
(public member function of std::basic_ios<CharT,Traits>) [edit]
checks if end-of-file has been reached
(public member function of std::basic_ios<CharT,Traits>) [edit]
checks if an error has occurred
(public member function of std::basic_ios<CharT,Traits>) [edit]
checks if a non-recoverable error has occurred
(public member function of std::basic_ios<CharT,Traits>) [edit]
checks if an error has occurred (synonym of fail())
(public member function of std::basic_ios<CharT,Traits>) [edit]
checks if no error has occurred (synonym of !fail())
(public member function of std::basic_ios<CharT,Traits>) [edit]
returns state flags
(public member function of std::basic_ios<CharT,Traits>) [edit]
sets state flags
(public member function of std::basic_ios<CharT,Traits>) [edit]
modifies state flags
(public member function of std::basic_ios<CharT,Traits>) [edit]
Formatting
copies formatting information
(public member function of std::basic_ios<CharT,Traits>) [edit]
manages the fill character
(public member function of std::basic_ios<CharT,Traits>) [edit]
Miscellaneous
manages exception mask
(public member function of std::basic_ios<CharT,Traits>) [edit]
sets the locale
(public member function of std::basic_ios<CharT,Traits>) [edit]
manages associated stream buffer
(public member function of std::basic_ios<CharT,Traits>) [edit]
manages tied stream
(public member function of std::basic_ios<CharT,Traits>) [edit]
narrows characters
(public member function of std::basic_ios<CharT,Traits>) [edit]
widens characters
(public member function of std::basic_ios<CharT,Traits>) [edit]

Inherited from std::ios_base

Member functions

Formatting
manages format flags
(public member function of std::ios_base) [edit]
sets specific format flag
(public member function of std::ios_base) [edit]
clears specific format flag
(public member function of std::ios_base) [edit]
manages decimal precision of floating point operations
(public member function of std::ios_base) [edit]
manages field width
(public member function of std::ios_base) [edit]
Locales
sets locale
(public member function of std::ios_base) [edit]
returns current locale
(public member function of std::ios_base) [edit]
Internal extensible array
[static]
returns a program-wide unique integer that is safe to use as index to pword() and iword()
(public static member function of std::ios_base) [edit]
resizes the private storage if necessary and access to the long element at the given index
(public member function of std::ios_base) [edit]
resizes the private storage if necessary and access to the void* element at the given index
(public member function of std::ios_base) [edit]
Miscellaneous
registers event callback function
(public member function of std::ios_base) [edit]
sets whether C++ and C I/O libraries are interoperable
(public static member function of std::ios_base) [edit]
Member classes
stream exception
(public member class of std::ios_base) [edit]
initializes standard stream objects
(public member class of std::ios_base) [edit]

Member types and constants

Type Explanation
stream open mode type

The following constants are also defined:

Constant Explanation[edit]
app seek to the end of stream before each write[edit]
binary open in binary mode[edit]
in open for reading[edit]
out open for writing[edit]
trunc discard the contents of the stream when opening[edit]
ate seek to the end of stream immediately after open[edit]
noreplace (C++23) open in exclusive mode[edit]

(typedef) [edit]
formatting flags type

The following constants are also defined:

Constant Explanation[edit]
dec use decimal base for integer I/O: see std::dec[edit]
oct use octal base for integer I/O: see std::oct[edit]
hex use hexadecimal base for integer I/O: see std::hex[edit]
basefield dec | oct | hex. Useful for masking operations[edit]
left left adjustment (adds fill characters to the right): see std::left[edit]
right right adjustment (adds fill characters to the left): see std::right[edit]
internal internal adjustment (adds fill characters to the internal designated point): see std::internal[edit]
adjustfield left | right | internal. Useful for masking operations[edit]
scientific generate floating point types using scientific notation, or hex notation if combined with fixed: see std::scientific[edit]
fixed generate floating point types using fixed notation, or hex notation if combined with scientific: see std::fixed[edit]
floatfield scientific | fixed. Useful for masking operations[edit]
boolalpha insert and extract bool type in alphanumeric format: see std::boolalpha[edit]
showbase generate a prefix indicating the numeric base for integer output, require the currency indicator in monetary I/O: see std::showbase[edit]
showpoint generate a decimal-point character unconditionally for floating-point number output: see std::showpoint[edit]
showpos generate a + character for non-negative numeric output: see std::showpos[edit]
skipws skip leading whitespace before certain input operations: see std::skipws[edit]
unitbuf flush the output after each output operation: see std::unitbuf[edit]
uppercase replace certain lowercase letters with their uppercase
equivalents in certain output operations: see std::uppercase[edit]

(typedef) [edit]
state of the stream type

The following constants are also defined:

Constant Explanation[edit]
goodbit no error[edit]
badbit irrecoverable stream error[edit]
failbit input/output operation failed (formatting or extraction error)[edit]
eofbit associated input sequence has reached end-of-file[edit]

(typedef) [edit]
seeking direction type

The following constants are also defined:

Constant Explanation[edit]
beg the beginning of a stream[edit]
end the ending of a stream[edit]
cur the current position of stream position indicator[edit]

(typedef) [edit]
specifies event type
(enum) [edit]
callback function type
(typedef) [edit]

[edit] Notes

Feature-test macro Value Std Feature
__cpp_lib_fstream_native_handle 202306L (C++26) native handles support

[edit] Example

#include <fstream>
#include <iostream>
#include <string>
 
int main()
{
    std::string filename = "Test.b";
    {
        std::ofstream ostrm(filename, std::ios::binary);
        double d = 3.14;
        ostrm.write(reinterpret_cast<char*>(&d), sizeof d); // binary output
        ostrm << 123 << "abc" << '\n';                      // text output
    }
 
    // read back
    std::ifstream istrm(filename, std::ios::binary);
    double d;
    istrm.read(reinterpret_cast<char*>(&d), sizeof d);
    int n;
    std::string s;
    istrm >> n >> s;
    std::cout << " read back: " << d << ' ' << n << ' ' << s << '\n';
}

Output:

read back: 3.14 123 abc