Set or add std :: ofstream by default?

If you call the std::ofstream without std::ofstream flags, the default flag is ios_base::out . But does this ios_base::trunc or ios_base::app ?

In other words, if you already have a non-empty file "past.txt" in your file system, and you call

 std::ofstream stream( "past.txt" ); stream << "new content"; 

Will new content be added to the previous "past.txt" content or will it replace the previous content?

+5
source share
1 answer

Short version

The standard is basically spaghetti on this, but ultimately it comes down to saying that it is the equivalent of the word fopen(const char*, "w") (27.9.1.4 [filebuf.members]), which then points to the ISO standard C 7.9

Testing this gives us §7.19.5.3, the “fopen Function”, which defines the behavior when passing “w”:

w crop to zero length or create a text file for writing


Long version

If you want to follow the spaghetti path, start with 27.9.1.11 [ofstream.cons], which describes the behavior of the constructor as

Effects: Creates a class basic_ofstream<charT,traits> object class basic_ofstream<charT,traits> , initializing the base class with basic_ostream(&sb ) and initializing sb with basic_filebuf<charT,traits>()) (27.7.3.2, 27.9.1.2), then calls rdbuf()->open(s, mode|ios_base::out) . If this function returns a null pointer, calls setstate(failbit) .

Where rdbuf() returns basic_filebuf<charT,traits>* (27.9.1.13 [ofstream])

Which brings us to 27.9.1.1 [filebuf], or more specifically, 27.9.1.4 [filebuf.members], which describes the open function:

 basic_filebuf<charT,traits>* open(const char* s, ios_base::openmode mode); 

a

Effects: if is_open() != false , returns a null pointer. Otherwise, initializes filebuf as needed. Then it opens the file, if possible, whose name is NTBS s (as if it were calling std::fopen(s,modstr) ). NTBS modstr determined from mode & ~ios_base::ate , as indicated in table 132. If mode does not have any combination of flags shown in the table, then the failure does not work.

NTBS: null-terminated byte string

Table 132 describes the equivalence rules between C ++ ios_base::openmode and C-style stdio strings:

 Table 132 — File open modes | | 'ios_base' flag combination | 'stdio' equivalent | | binary | in | out | trunc | app | | | | | + | | | "w" | | etc... | 

Which leads us to a footnote on the same page that states:

... the signatures of the functions fopen(const char*, const char*) and fseek(FILE*, long, int) declared in <cstdio> (27.9.2).

Which sends us, predictably, 27.9.2 [c.files], which provides an almost useless table 134, but then refers to the C standard:

See also: ISO C 7.9, Amendment 1 4.6.2.

What I'm talking about in the main part of this answer.

+18
source

All Articles