0

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.

Paolo.Bolzoni
  • 2,416
  • 1
  • 18
  • 29

3 Answers3

2

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;
}
Community
  • 1
  • 1
Anand Rathi
  • 790
  • 4
  • 11
1

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' (e.g. 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.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
  • 1
    So, you mean: no, you cannot use a FILE* to put or get from a C++ stream? – Paolo.Bolzoni Jun 19 '13 at 16:31
  • I mean, you can't MIX them using the same file at the same time. As long as the file is closed from using it in one way. But you can certainly use both in C++. Just not from the same file at the same time. – Mats Petersson Jun 19 '13 at 16:36
  • And that would apply if you open the same file twice using `FILE *` too - it's not meant to work that way. – Mats Petersson Jun 19 '13 at 16:37
0

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. :)

Prof. Falken
  • 24,226
  • 19
  • 100
  • 173