1

Can I open a file with C functions (fopen) and assign that handle to a C++ file stream (fstream...)?

Reason for asking: I want to handle UTF8 on windows but the fstream class has only a const char* ctor/open method. So I need to open it using the C API and then make a stream object use it.

It might even be possible with the boost stream library as it often allows specifying your own sinks/sources but I don't know where to start.

Clarification: I want to open a file with a path given as an UTF8 string. So the file open method must support UTF8 paths which fstream does not. The MSVC extension accepting a const wchar_t* does help, but MinGW does not provide these overloads. So I'd need to use wfopen on windows instead.

Flamefire
  • 5,313
  • 3
  • 35
  • 70
  • I may be missing something but `UTF-8` requires normal width `char*` buffers. Also the fstream open method only deals with the file name so it makes no difference what encoding the file contains. Can you be more specific about why opening files with fstream is not working? – Galik Sep 26 '17 at 03:58
  • Reading strings from an `fstream` depends on which locale is assigned to it. – Remy Lebeau Sep 26 '17 at 19:41
  • The filename is UTF8. Added that above – Flamefire Sep 27 '17 at 01:13
  • Note: Related to https://stackoverflow.com/questions/46397007/utf-8-names-with-boostfilestream-under-mingw – Flamefire Sep 27 '17 at 21:57

1 Answers1

1

Can I open a file with C functions (fopen) and assign that handle to a C++ file stream (fstream...)?

Not directly, no. But you can write (or find) a custom std::streambuf derived class that handles I/O using FILE*, and then assign an instance of that class to a standard std::istream object. See the implementation of std::basic_filebuf to help you, or GNU's stdio_filebuf class.

I want to open a file with a path given as an UTF8 string. So the file open method must support UTF8 paths which fstream does not. The MSVC extension accepting a const wchar_t* does help, but MinGW does not provide these overloads. So I'd need to use wfopen on windows instead.

Most Unicode APIs on Windows do not support UTF-8, only UTF-16. Thus the wchar_t overloads in Visual C++ and other compatible compilers. Mingw simply does not support those extensions. There are 3rd party solutions, though. Such as Pathie (see the Pathie::ifstream and Pathie::ofstream classes).

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • As added in the question: The filename is UTF8. Do you happen to know an implementation that works with that or if there is a boost component for this? – Flamefire Sep 27 '17 at 01:14
  • Thank you! The library boost:nowide is also helpful as it provides the `iofstream` classes. Pathie could probably replace all the boost::filesystem stuff but I'd rather complement them. Or do you have any comments/experience with either? – Flamefire Sep 27 '17 at 02:47