4

I am using g++ to compile some code. I wrote the following snippet:

bool WriteAccess = true;
string Name = "my_file.txt";
ofstream File;
ios_base::open_mode Mode = std::ios_base::in | std::ios_base::binary;
if(WriteAccess)
  Mode |= std::ios_base::out | std::ios_base::trunc;
File.open(Name.data(), Mode);

And I receive these errors... any idea why?

Error 1: invalid conversion from ‘int’ to ‘std::_Ios_Openmode’
Error 2: initializing argument 2 of ‘std::basic_filebuf<_CharT, _Traits>* std::basic_filebuf<_CharT, _Traits>::open(const char*, std::_Ios_Openmode) [with _CharT = char, _Traits = std::char_traits]’

As far as I could tell from a Google search, g++ is actually breaking the C++ standard here. Which I find quite astonishing, since they generally conform very strictly to the standard. Is this the case? Or am I doing something wrong.

My reference for the standard: http://www.cplusplus.com/reference/iostream/ofstream/open/

Dylan Klomparens
  • 2,853
  • 7
  • 35
  • 52
  • Besides correcting the type name, `Name.c_str()` should be used instead of `Name.data()`, since std::string::data() does not return a null-terminated character array. – Cubbi Jun 03 '10 at 20:10

3 Answers3

4

openmode is the correct type, not open_mode.

ergosys
  • 47,835
  • 5
  • 49
  • 70
  • I debugged the same issue for more than 2 hours. It's pure evil. Almost as evil as `#define true false`. – Calmarius Jul 29 '19 at 09:48
2

This:

ios_base::open_mode Mode = std::ios_base::in | std::ios_base::binary;

should be:

std::ios_base::openmode Mode = std::ios_base::in | std::ios_base::binary;

Note the lack of _ in openmode.

(I had to add these lines and put your code in a function to get your snippet to compile.

#include <string>
#include <fstream>

using std::string;
using std::ofstream;
using std::ios_base;

)

CB Bailey
  • 755,051
  • 104
  • 632
  • 656
2

g++ is not totally conforming, but it's not the reason for the error here.

The type of mode should be

std::ios_base::openmode

instead of

std::ios_base::open_mode

The latter is an old, deprecated API. It is still specified in Annex D of the C++ standard, so the compiler still have to support it.

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005