Re: Надо сконвертить FILE* в ofstream
От: MaximE Великобритания  
Дата: 10.12.04 20:04
Оценка: 27 (4)
wrote:

> Это возможно?


Да.

> если брать fstream.h, а не fstream то у ofstream есть метод attach

> и тогда:

[]

> в fstream с этим как-то напряг:


[]

Ты можешь написать собственный streambuf, который будет легким враппером над fread/fwrite.

Пример: буфер + поток в одном флаконе.

#include <stdio.h>
#include <iostream>

class filehandle_stream : private std::streambuf, public std::iostream
{
private:
     FILE* f_;

public:
     filehandle_stream(FILE* f) : std::iostream(this), f_(f) {}
     ~filehandle_stream() { if(f_) fclose(f_); }

     FILE* release() { FILE* t = f_; f_ = 0; return t; }

public:
     typedef std::streambuf::traits_type traits_type;
     typedef std::streambuf::char_type char_type;
     typedef std::streambuf::int_type int_type;

private: // интерфейс вывода
     std::streamsize xsputn(char_type const* s, std::streamsize n)
     {
         return fwrite(s, 1, n, f_);
     }

     int_type overflow(int_type c)
     {
         if(!traits_type::eq_int_type(c, traits_type::eof()))
         {
             char_type const t = traits_type::to_char_type(c);
             this->filehandle_stream::xsputn(&t, 1);
         }
         return !traits_type::eof();
     }

     int sync() { return !fflush(f_) ? 0 : -1; }

private: // интерфейс ввода
     std::streamsize xsgetn(char_type* s, std::streamsize n)
     {
         return fread(s, 1, n, f_);
     }

     int_type underflow()
     {
         char_type c;
         return 1 == this->xsgetn(&c, 1) ? traits_type::to_int_type(c) : traits_type::eof();
     }
};

int main()
{
     filehandle_stream s(stdout);
     s << "hey!" << std::endl;
     s.release();
}


--
Maxim Yegorushkin
Posted via RSDN NNTP Server 1.9 delta
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.