Michele De Stefano's C++ Utilities
cfile_sink_src.cpp

This is an example on how to use C++ devices for C FILE*.

// cfile_sink_src.cpp
//
// Copyright (c) 2009 - Michele De Stefano (micdestefano@users.sourceforge.net)
//
// Distributed under the MIT License (See accompanying file LICENSE)
#include <iostream>
#include <boost/iostreams/stream_buffer.hpp>
namespace bios = boost::iostreams;
int main(int argc,char *argv[]) {
using namespace std;
if (argc != 2) {
cerr << "\nSyntax:\n\t" << argv[0] << " <file name>\n" << endl;
return EXIT_FAILURE;
}
FILE *fp(NULL);
// Open a file with fopen
fp = fopen(argv[1],"w");
// Instantiate the sink
mds_fu::cFile_Sink fsink(fp);
// Instantiate the stream_buffer
bios::stream_buffer<mds_fu::cFile_Sink> sbuf;
// Instantiate an std output stream, connecting it to the buffer
ostream ofs(&sbuf);
// Connect the buffer to the file sink
// (you could do this also before the ofs instantiation)
sbuf.open(fsink);
// Activate stream exceptions
ofs.exceptions(ios::failbit | ios::badbit);
double val = 45.6;
// Write a binary value
ofs.write(reinterpret_cast<char*>(&val),sizeof(double));
// Flush the value to the file
ofs.flush();
// Try to disconnect the buffer from the sink
sbuf.close();
// Re-connect the buffer to the sink
sbuf.open(fsink);
// Write something to file
ofs << "This is a test string" << endl;
// Flush before next operations
ofs.flush();
// Try the seekp function
ofs.seekp(-5,ios::cur);
// Overwrite from the current position
ofs << "word" << endl;
// Close the file
fclose(fp); fp = NULL;
// Disconnect the buffer
sbuf.close();
// Re-open the file in append mode
fp = fopen(argv[1],"ab");
// Re-set the file pointer into the sink
fsink.set_FILEp(fp);
// Re-connect the buffer to the sink
sbuf.open(fsink);
// Write something
ofs << "Mic" << endl;
// Remember to flush
ofs.flush();
// Try to seek in a file in append mode
ofs.seekp(-3,ios::end);
ofs << "Des" << std::endl; // It is written at the end, because the file is opened
// in append mode
// Close the file
fclose(fp); fp = NULL;
// Disconnect the buffer
sbuf.close();
// Re-open in read-binary
fp = fopen(argv[1],"rb");
// Instantiate a source device
mds_fu::cFile_Source fsource(fp);
// Instantiate a new buffer for the source
bios::stream_buffer<mds_fu::cFile_Source> sbuf2;
// Connect the buffer to the source device
sbuf2.open(fsource);
// Instantiate an input stream and connect it to
// the prepared buffer
istream ifs(&sbuf2);
// Activate stream exceptions
ifs.exceptions(ios::badbit | ios::failbit);
// Try to seek
ifs.seekg(-4,ios::end);
string str;
// Extract a string
ifs >> str;
cout << "Read string: " << str << endl;
// Seek again
ifs.seekg(0,ios::beg);
// Read a double
ifs.read(reinterpret_cast<char*>(&val),sizeof(double));
cout << "Value read: " << val << endl;
fclose(fp); fp = NULL;
return EXIT_SUCCESS;
}