Does fstream take a constant character array as a parameter or a dynamic one?

50 views Asked by At

I am trying to send an fstream object to a function, and I provided the name of the file as a string. Now I want to type-cast the string into a character array because fstream takes a character array. However, I am wondering whether to make it static or constant or not. Also, if I wanted to make it static, should I use static_cast<const char*> or should I just use str.c_str()?

I searched the Internet but wasn't successful finding the answer I needed.

1

There are 1 answers

2
user12002570 On

I want to type cast the string into character array because fstream takes character array.

Your assumption that fstream only takes a character array is wrong. Starting from C++11, it also has a ctor that takes a std::string. So you don't need to use c_str or any cast as you can just directly use std::string.

From std::fstream:

explicit basic_fstream( const std::string& filename,

                        std::ios_base::openmode mode
                            = std::ios_base::in | std::ios_base::out );

Why don't the std::fstream classes take a std::string?