Edit: here is something (commented in French -- it comes from the french FAQ of fr.comp.lang.c++ --, I have no time for translation and think it is better to leave them than to remove them) which wraps FILE* call into a streambuf. This also is a show case of a use of private inheritance: ensuring that what could be a member is initialized before a base class. In the case of IOStream, the base class could as well receive a NULL pointer and then the member init() used to set the streambuf.


#include <stdio.h>
#include <assert.h>

#include <iostream>
#include <streambuf>

// streambuf minimal encapsulant un FILE*
//    - utilise les tampons de FILE donc n'a pas de tampon interne en
//      sortie et a un tampon interne de taille 1 en entree car l'interface
//      de streambuf ne permet pas de faire moins;
//    - ne permet pas la mise en place d'un tampon
//    - une version plus complete devrait permettre d'acceder aux
//      informations d'erreur plus precises de FILE* et interfacer aussi
//      les autres possibilites de FILE* (entre autres synchroniser les
//      sungetc/sputbackc avec la possibilite correspondante de FILE*)

class FILEbuf: public std::streambuf
{
public:

  explicit FILEbuf(FILE* cstream);
  // cstream doit etre non NULL.

protected:

  std::streambuf* setbuf(char_type* s, std::streamsize n);

  int_type overflow(int_type c);
  int      sync();

  int_type underflow();

private:

  FILE*    cstream_;
  char     inputBuffer_[1];
};

FILEbuf::FILEbuf(FILE* cstream)
  : cstream_(cstream)
{
  // le constructeur de streambuf equivaut a
  // setp(NULL, NULL);
  // setg(NULL, NULL, NULL);
  assert(cstream != NULL);
}

std::streambuf* FILEbuf::setbuf(char_type* s, std::streamsize n)
{
  // ne fait rien, ce qui est autorise.  Une version plus complete
  // devrait vraissemblablement utiliser setvbuf
  return NULL;
}

FILEbuf::int_type FILEbuf::overflow(int_type c)
{
  if (traits_type::eq_int_type(c, traits_type::eof())) {
    // la norme ne le demande pas exactement, mais si on nous passe eof
    // la coutume est de faire la meme chose que sync()
    return (sync() == 0
        ? traits_type::not_eof(c)
        : traits_type::eof());
  } else {
    return ((fputc(c, cstream_) != EOF)
        ? traits_type::not_eof(c)
        : traits_type::eof());
  }
}

int FILEbuf::sync()
{
  return (fflush(cstream_) == 0
      ? 0
      : -1);
}

FILEbuf::int_type FILEbuf::underflow()
{
  // Assurance contre des implementations pas strictement conformes a la
  // norme qui guaranti que le test est vrai.  Cette guarantie n'existait
  // pas dans les IOStream classiques.
  if (gptr() == NULL || gptr() >= egptr()) {
    int gotted = fgetc(cstream_);
    if (gotted == EOF) {
      return traits_type::eof();
    } else {
      *inputBuffer_ = gotted;
      setg(inputBuffer_, inputBuffer_, inputBuffer_+1);
      return traits_type::to_int_type(*inputBuffer_);
    }
  } else {
    return traits_type::to_int_type(*inputBuffer_);
  }
}

// ostream minimal facilitant l'utilisation d'un FILEbuf
// herite de maniere privee de FILEbuf, ce qui permet de s'assurer
// qu'il est bien initialise avant std::ostream

class oFILEstream: private FILEbuf, public std::ostream 
{
public:
  explicit oFILEstream(FILE* cstream);
};

oFILEstream::oFILEstream(FILE* cstream)
  : FILEbuf(cstream), std::ostream(this)
{
}

// istream minimal facilitant l'utilisation d'un FILEbuf
// herite de maniere privee de FILEbuf, ce qui permet de s'assurer
// qu'il est bien initialise avant std::istream

class iFILEstream: private FILEbuf, public std::istream
{
public:
  explicit iFILEstream(FILE* cstream);
};

iFILEstream::iFILEstream(FILE* cstream)
  : FILEbuf(cstream), std::istream(this)
{
}

// petit programme de test
#include <assert.h>
int main(int argc, char* argv[])
{
  FILE* ocstream = fopen("result", "w");
  assert (ocstream != NULL);
  oFILEstream ocppstream(ocstream);
  ocppstream << "Du texte";
  fprintf(ocstream, " melange");
  fclose(ocstream);
  FILE* icstream = fopen("result", "r");
  assert (icstream != NULL);
  iFILEstream icppstream(icstream);
  std::string word1;
  std::string word2;
  icppstream >> word1;
  icppstream >> word2;
  char buf[1024];
  fgets(buf, 1024, icstream);
  std::cout << "Got :" << word1 << ':' << word2 << ':' << buf << '\n';
}

This tells you that \red is not defined, this is simply wrong syntax


    \documentclass{book}
%mwe_clisting2


%Rétablissement des polices vectorielles
%Pour retourner dans le droit chemin, vous  pouvez passer par le package ae ou bien utiliser les fontes modernes, voire les deux :
\usepackage{ae,lmodern} % ou seulement l'un, ou l'autre, ou times etc.
\usepackage[english,french]{babel}
\usepackage[utf8]{inputenc}
%%% Note that this is font encoding (determines what kind of font is used), not input encoding. 
\usepackage[T1]{fontenc}
\usepackage[cyr]{aeguill}
\usepackage{tikz}
\tikzset{coltria/.style={fill=red!15!white}}
\usepackage{tcolorbox}
\tcbuselibrary{listings,breakable,skins,documentation,xparse}
\lstdefinestyle{Clst}{ 
    literate=
    {á}{{\'a}}1
    {à}{{\`a }}1
    {ã}{{\~a}}1
    {é}{{\'e}}1
    {ê}{{\^e}}1
    {î}{{\^i}}1
    {oe}{{\oe}}1
    {í}{{\'i}}1
    {ó}{{\'o}}1
    {õ}{{\~o}}1
    {ú}{{\'u}}1
    {ü}{{\"u}}1
    {ç}{{\c{c}}}1,    
    numbers=left, 
    numberstyle=\small, 
    numbersep=8pt, 
    frame = none, 
    language=C, 
    framexleftmargin=5pt,            % la marge à  gauche du code
    % test pour améliorer la présentation du code
    upquote=true,
    columns=flexible,
    basicstyle=\ttfamily,
    basicstyle=\small, % ==> semble optimal \tiny est vraiment trop petit
    % provoque une erreur texcsstyle=*\color{blue},
    commentstyle=\color{green},    % comment style
    keywordstyle=\color{blue},       % keyword style
    rulecolor=\color{black},         % if not set, the frame-color may be changed on line-breaks within not-black text (e.g. comments (green here))
    showspaces=false,                % show spaces everywhere adding particular underscores; it overrides 'showstringspaces'        
    showtabs=false,                  % show tabs within strings adding particular underscores
    stringstyle=\color{cyan},     % string literal style
    numbers=none, 
    tabsize=4,
    % pour couper les lignes trop longues
    breaklines,
    breakindent=1.5em, %?indente?de?3?caracteres?vers?la?droite
    escapechar=µ,% pour escape en latex
    % pour l'encodage à l'intérieur des listing utf8 et latin1    ?????
    %   inputencoding=utf8/latin1,
    morekeywords=[2]{ % j'ajoute une catégorie de mots-clés 
        %%% pour tri sur le 5ieme caractere
        gtk_window_new,
        gtk_window_set_title,
        gtk_window_set_resizable,
        gtk_window_get_resizable,
        gtk_window_is_maximized,
        gtk_window_maximize,
        gtk_window_unmaximize,
        gtk_window_fullscreen,
        gtk_window_fullscreen_on_monitor,
        gtk_window_unfullscreen,
        %%%%%%%%%%%
        gdk_rgba_parse,
        gdk_rgba_parse,
        gdk_rgba_parse,
        gdk_rgba_parse,
        % dernier sans la virgule
    },
    morekeywords=[3]{ %% j'ajoute une autre catégorie de mots-clés 
        %%% pour tri sur le 3ieme caractere
        G_TYPE_NONE,
        G_TYPE_INTERFACE,
        G_TYPE_CHAR,
        G_TYPE_UCHAR,
        G_TYPE_BOOLEAN,
        G_TYPE_INT,
        G_TYPE_UINT,
        G_TYPE_LONG,
        % dernier sans la virgule
    },
    morekeywords=[4]{ %% j'ajoute une autre catégorie de mots-clés 
        %%% pour tri sur le 1er caractere
        GtkSourceLanguageManager, 
        GtkSourceSmartHomeEndType,
        GtkSourceMarkAttributes,
        GtkSourceDrawSpacesFlags,
        GtkSourceCompletion,
        GtkSourceGutter,
        GtkSourceBackgroundPatternType,
        Container_set_border_width,
        GtkSourceSearchContext,
        GtkFileChooserAction,
        gboolean,
        %%%%%%
        cairo_rectangle,
        cairo_fill,
        % dernier sans la virgule
    },
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %%%Traitement des mots-clefs type gtk_xxxxx
    keywordstyle=[2]\monstyleblue, %%%\color{blue}, % je leur donne une coloration spéciale ds le texte
    %% Intégration dans l'index OK
    moreindex={[1][keywords2]},    % ces mots-clés sont ajoutés à  l'index?oui
    %% gtk_xxxx trié par xxxx  ca fonctionne sur tout l'index
    indexstyle={[1]\indexgtk},      % par le biais de macro \indexgtk
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %%%Traitement des mots-clefs type g_xxxxx
    keywordstyle=[3]\monstylegreen, %%%\color{green}, % je leur donne une coloration spéciale ds le texte
    %% Intégration dans l'index OK
    moreindex={[3][keywords3]},    % ces mots-clés sont ajoutés à  l'index?oui
    %% gtk_xxxx trié par xxxx  ca fonctionne sur tout l'index
    indexstyle={[3]\indexglib},      % par le biais de ma macro tri 3ieme
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %%%Traitement des mots-clefs type GtkSourceSmartHomeEndType
    keywordstyle=[4]\monstylebrown,     %%%\color{brown}, % je leur donne une coloration spéciale ds le texte
    %% Intégration dans l'index OK
    moreindex={[4][keywords4]},    % ces mots-clés sont ajoutés à  l'index?oui
    %% xxxx trié par xxxx  ca fonctionne sur tout l'index
    indexstyle={[4]\indextype},          % tri sur le mot entier
}
%---------------------------------------------------------------------------------------
%------------------------------ box dédié au code langage C ----------------------------
%---------------------------------------------------------------------------------------
\newtcblisting{Clisting}[2][]{empty,breakable,leftrule=5mm,left=2mm,
    %frame style={fill,top color=red!75!black,bottom color=red!75!black,middle color=red},
    frame style={fill,top color=green!75!black,bottom color=green!75!black,middle color=green},
    listing only,
    listing engine=listings, 
    listing options={style=Clst,tabsize=4,breaklines,
        breakindent=1.5em,columns=fullflexible},
    %       keywordstyle=\color{red}},
    colback=yellow!15!white,
    % code for unbroken boxes:
    frame code={\path[tcb fill frame] (frame.south west)--(frame.north west)
        --([xshift=-5mm]frame.north east)--([yshift=-5mm]frame.north east)
        --([yshift=5mm]frame.south east)--([xshift=-5mm]frame.south east)--cycle; },
    interior code={\path[tcb fill interior] (interior.south west)--(interior.north west)
        --([xshift=-4.8mm]interior.north east)--([yshift=-4.8mm]interior.north east)
        --([yshift=4.8mm]interior.south east)--([xshift=-4.8mm]interior.south east)
        --cycle; },
    attach boxed title to top center={yshift=-2mm},
    title=\fcolorbox{black}{black}{\color{red}{#2}},
    % code for the first part of a break sequence:
    skin first is subskin of={emptyfirst}{%
        frame code={\path[tcb fill frame] (frame.south west)--(frame.north west)
            --([xshift=-5mm]frame.north east)--([yshift=-5mm]frame.north east)
            --(frame.south east)--cycle;
            \path[coltria] ([xshift=2.5mm,yshift=1mm]frame.south west) -- +(120:2mm)
            -- +(60:2mm)-- cycle; },
        interior code={\path[tcb fill interior] (interior.south west|-frame.south)
            --(interior.north west)--([xshift=-4.8mm]interior.north east)
            --([yshift=-4.8mm]interior.north east)--(interior.south east|-frame.south)
            --cycle; },
    },%
    % code for the middle part of a break sequence:
    skin middle is subskin of={emptymiddle}{%
        frame code={\path[tcb fill frame] (frame.south west)--(frame.north west)
            --(frame.north east)--(frame.south east)--cycle;
            \path[coltria] ([xshift=2.5mm,yshift=-1mm]frame.north west) -- +(240:2mm)
            -- +(300:2mm) -- cycle;
            \path[coltria] ([xshift=2.5mm,yshift=1mm]frame.south west) -- +(120:2mm)
            -- +(60:2mm) -- cycle;
        },
        interior code={\path[tcb fill interior] (interior.south west|-frame.south)
            --(interior.north west|-frame.north)--(interior.north east|-frame.north)
            --(interior.south east|-frame.south)--cycle; },
    },
    % code for the last part of a break sequence:
    skin last is subskin of={emptylast}{%
        frame code={\path[tcb fill frame] (frame.south west)--(frame.north west)
            --(frame.north east)--([yshift=5mm]frame.south east)
            --([xshift=-5mm]frame.south east)--cycle;
            \path[coltria] ([xshift=2.5mm,yshift=-1mm]frame.north west) -- +(240:2mm)
            -- +(300:2mm) -- cycle;
        },
        interior code={\path[tcb fill interior] (interior.south west)
            --(interior.north west|-frame.north)--(interior.north east|-frame.north)
            --([yshift=4.8mm]interior.south east)--([xshift=-4.8mm]interior.south east)
            --cycle; },#1}}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% attention dans les 3 commandes ci-dessous l'activation simultanée de \marginpar{\scriptsize  provoque une situation ingérable par latex
\newcommand{\monstylered}[1] % attention ici le 1 c'est un seul paramètre !!!!!
{\color{red}{\emph{#1}}
}
\newcommand{\monstyleblue}[1] % attention ici le 1 c'est un seul paramètre !!!!!
{\color{blue}{\emph{#1}}
}
\newcommand{\monstylebrown}[1] % attention ici le 1 c'est un seul paramètre !!!!!
{\color{brown}{\emph{#1}}
}

\newcommand{\monstylegreen}[1] % attention ici le 1 c'est un seul paramètre !!!!!
{\color{green}{\emph{#1}}
}
%----------------------- Fin Traitement des listing ------------------------------

% --------------------- Macros pour indexation des mots clefs --------------------

% macro pour fabriquer le fichier d'index
\usepackage{makeidx}
\makeindex
% fabrication de l'index 

%makeindex mwe_clisting2.idx -s perso.ist

%---------------------------------------------------------------------------------
%%%%%% tri a partir du 5ieme element gtk_XXXX et couleur index blue
\makeatletter
\def\@indexgtk@i#1#2#3#4#5,{\index{#5@\monstyleblue{#1#2#3#4#5}}}
\def\indexgtk#1{\@indexgtk@i#1,}
\makeatother


%---------------------------------------------------------------------------------
%%%%% tri a partir du 3ieme element G_NONE  et couleur index green
\makeatletter
\def\@indexglib@i#1#2#3,{\index{#3@\monstylegreen{#1#2#3}}}
\def\indexglib#1{\@indexglib@i#1,}
\makeatother

%%%%%% tri a partir du 1er element MANQUE MISE EN ITALIQUE et couleur index marron
\makeatletter
\def\@indextype@i#1,{\index{#1@\monstylebrown{#1}}}
\def\indextype#1{\@indextype@i#1,}
\makeatother
%---------------------------------------------------------------------------------------

\begin{document}

Voici l'étape qui a toute les chances de ne pas être lue au début mais plutôt quand on est dans une belle impasse. Croire qu'on va s'en sortir sans un minimum de méthode n'est pas viable dans le projet que je vous propose de suivre.
Aidez-moi à conjurer le mauvais sort, et lisez avec attention cette liste de recommandation qui relève du bon sens pratique du développeur expérimenté qu'il aurait aimé découvrir dès ses premiers pas.


\begin{Clisting} {fonction draw\_func}
    void draw_func (GtkDrawingArea *da,
    cairo_t        *cr,
    int             width,
    int             height,
    gpointer        data)
    {
        GdkRGBA red, green, yellow, blue;
        double w, h;

        w = width / 2.0;
        h = height / 2.0;

        gdk_rgba_parse (&red, "red");
        gdk_rgba_parse (&green, "green");
        gdk_rgba_parse (&yellow, "yellow");
        gdk_rgba_parse (&blue, "blue");

        gdk_cairo_set_source_rgba (cr, &red);
        cairo_rectangle (cr, 0, 0, w, h);
        cairo_fill (cr);

        gdk_cairo_set_source_rgba (cr, &green);
        cairo_rectangle (cr, w, 0, w, h);
        cairo_fill (cr);

        gdk_cairo_set_source_rgba (cr, &yellow);
        cairo_rectangle (cr, 0, h, w, h);
        cairo_fill (cr);

        gdk_cairo_set_source_rgba (cr, &blue);
        cairo_rectangle (cr, w, h, w, h);
        cairo_fill (cr);
    }
    ...
    gtk_drawing_area_set_draw_func (area, draw, NULL, NULL);
\end{Clisting}

\begin{Clisting}{here problem with accent}
    gboolean TEST1 = TRUE
    if (TEST1)
    {
        /** nouvel essai nouvelle méthode à tester **/
        ...
    }
    else
    {
        /** ancien bloc fonctionnel qui buggue **/
        ...
    }   
\end{Clisting}

\begin{Clisting}{Run ok with colorisation index}
    gtk_window_new  
    gtk_window_set_title  
    gtk_window_set_resizable  
    gtk_window_get_resizable  
    gtk_window_is_maximized  
    gtk_window_maximize  
    gtk_window_unmaximize  
    gtk_window_fullscreen  
    gtk_window_fullscreen_on_monitor  
    gtk_window_unfullscreen  

    G_TYPE_NONE  
    G_TYPE_INTERFACE  
    G_TYPE_CHAR  
    G_TYPE_UCHAR  
    G_TYPE_BOOLEAN  
    G_TYPE_INT  
    G_TYPE_UINT  
    G_TYPE_LONG  

    GtkSourceLanguageManager   
    GtkSourceSmartHomeEndType  
    GtkSourceMarkAttributes  
    GtkSourceDrawSpacesFlags  
    GtkSourceCompletion  
    GtkSourceGutter  
    GtkSourceBackgroundPatternType  
    Container_set_border_width  
    GtkSourceSearchContext  
    GtkFileChooserAction  
    gboolean  

\end{Clisting}
\printindex
\end{document}

Recommend

setup constants like this - Constants.Page.Title.MyCase - in C#?

Excel with Macro

UpdateAll and HABTM in CakePHP

apply check mark on table view in iphone using objective c?

remove duplicate values from an array in PHP and count the occurrence?

Sql server - how to insert single row into temporary table?

XElement default namespace on attributes provides unexpected behaviour

Find Colour Range

split byte[] array

A bounded BlockingQueue that doesn't block

remove whitespace from an XmlDocument

clean a string by removing anything that is not a letter in PHP

Adding a hyperlink to a PHP-generated table

How should I close a multi-line variable/comment in Python?

Tricky SQL SELECT Statement

highligh the row and column of a table when over a cell using jQuery?

Get pointer to class of instance variable in Objective-C

General programming - calling a non void method but not using value

Comparing DOM elements with jQuery

Problem: Sorting for GridView/ObjectDataSource changes depending on page

jsp error when using if-else with html

Redirecting browser using AJAX

Declaring variables inside a switch statement

emacs list-buffers behavior

Load an PEM encoded X.509 certificate into Windows CryptoAPI

SHA1 C# method equivalent in Perl?

Is int in C Always 32-bit?

General programming - else or else if for clarity

write content into pdf use iText?

add a conditional breakpoint in Xcode

iPhone: Post data to php page

Creating Enums from Entities

Reading uintvars (VLQs) into C# ints

Method delegation in Javascript/jQuery?

get a youtube's video static image using javascript?

NHibernate - easiest way to do a LIKE search against an integer column with Criteria API?

mute entire flex application?

Web Page Design Get Distorted in Desktop PC Monitor

make 100% width for 2 div

store changing data into a database?

Modify an Excel Shape from Delphi

Why is Perl script asking for 'global declaration' when I declare something in for loop?

iPhone crashes when I properly release pushed view controllers

Static Pointer to Dynamically allocated array

import the content of MS Access Database into combo box of Excel?

Reverse Spectrogram A La Aphex Twin in MATLAB

Xcode - Using #pragma mark

a string array be databound to a ListBox?

IE7 - Floated Image Disappears!

Excel: filter table rows by specified column value

Iphone Core Data crashing on Save

Selenium.IsElementPresent using a Select Option's text (C#)

Is there a point at which an Enum can get too bloated?

I get these weird characters when I try to print out a vector element!

jquery decode json object with double quoted keys

Need html text shown as a link to work with an iframe

Database blob holds multiline html code, how can I convert this into one line with php

When does Oracle index null column values?

bind a list of objects with composite-key to a checkbox list?

Best way to get rid of unwanted sql subselects?

jQuery dynamic selector

default a:hover overriding ones with classes ie6

get BOOL from id

Convert a Nokogiri document to a Ruby Hash

Where is the Fold LINQ Extension Method?

running a subset of JUnit @Test methods

ASP.NET MVC - style list item based on controller

create a PHP/MySQL powered image gallery from scratch?

Recursively ignoring files in the entire source tree in subversion

Ninject not firing?

WPF Binding Question

subprocess: deleting child processes in Windows

add lines to the top and bottom of a file in Perl?

Double-nested Routing

capture submit event using jQuery in an ASP.NET application?

Advantage of creating a generic repository vs. specific repository for each object?

is there a way to pause an NSTHread indefinitely and have it resumed from another thread?

Iphone OS Version 3.0.1 (7A400) - not supported by latest version of XCode

Comparison operators not supported for type 'System.Linq.IQueryable`1[System.Int32]'

Rails: Finding children of children in habtm activerecord relationships

Ext JS GroupingStore group DateTime column by just date?

The default look of Icefaces and how to customize it

Django: models last mod date and mod count

Printing out 25 most recently added tables

Javascript Regex: How to bold specific words with regex?

std::sort and binary '=' operator issue with a C++ struct

C++ : handle resources if constructors may throw exceptions (Reference to FAQ 17.4]

the best method for supporting screen sizes in a Web app?

see if an element in offscreen

troubles with jQuery mouseleave

Best way to parse a table in Ruby

Does Django have a built in way of getting the last app url the current user visited?

get the history of a file/folder property in SVN?

Why do I get a warning every time I use malloc?

Does using properties on an old-style python class cause problems

Flex Listening for Events Issue

get a div to resize its height to fit container?

Decode complex JSON in Python

Loading data in to a combo box is slow

the % operator in python for?