I need to use an existing C library in a C++ project. My problem is the C existing library uses FILE* as streams, is there a standard compliant way to use FILE* streams to put or to get from C++ streams?
I tried seeking FILE* in the C++11 standard, but it appears only if few examples.
-
EDIT, example.
We have a function which write in a FILE*:
fputs(char const*, FILE*)
We have an output C++ stream:
auto strm = std::cout;
Can I, in a standard compliant way, to use fputs to write to strm?
You can also think a similar input example with a C function that reads from a FILE* and a input C++ stream.
Check this answer ,
https://stackoverflow.com/a/5253726/1807864
#include <cstdio>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream ofs("test.txt");
ofs << "Writing to a basic_ofstream object..." << endl;
ofs.close();
int posix_handle = ::_fileno(::fopen("test.txt", "r"));
ifstream ifs(::_fdopen(posix_handle, "r")); // 1
string line;
getline(ifs, line);
ifs.close();
cout << "line: " << line << endl;
return 0;
}
The C++ standard, with very few exceptions says that C functionality is all included. Certainly all the stadnard C FILE *
functionality is supported [obviously subject to general support for FILE *
on the platform - an embedded system that doesn't have a 'files' (eg there is no storage) in general will hardly have much useful support for FILE *
- nor will C++ style fstream
work].
So, as long as you don't try to mix reading/writing to the same file from both C++ fstream
and C FILE *
at the same time, it should work just fine. You will need to close the file between C++ and C access, however.
As far as I understand, doing so is non-portable and non-standard . Whether it works in practice or not is another question. I would create wrapper classes around your legacy code, or use FILE* streams directly like in C - they are not that bad. :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.