Strange error: cannot convert from 'int' to 'ios_base :: openmode'

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 get these errors ... any idea why?

Error 1: invalid conversion from 'int to' std :: _ Ios_Openmode
Error 2: initialization of argument 2 from '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 can tell from a Google search, g ++ actually violates the C ++ standard. Which I find quite surprising, since they are generally very strictly in line with the standard. This is true? Or am I doing something wrong.

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

+4
source share
3 answers

openmode is the correct type, not open_mode.

+4
source

It:

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

it 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 so that your snippet is compiled.

 #include <string> #include <fstream> using std::string; using std::ofstream; using std::ios_base; 

)

+2
source

g ++ is not fully consistent, but that is not the cause of the error here.

The type of mode should be

 std::ios_base::openmode 

instead

 std::ios_base::open_mode 

The latter is an old, deprecated API. It is still listed in Appendix D of the C ++ standard, so the compiler must still support it.

+1
source

Source: https://habr.com/ru/post/1311781/


All Articles