C++ ifstream buffering from named pipe

Joshua Cole joshua.cole at anu.edu.au
Thu May 22 16:20:34 CST 2003


Hello,

I have a problem reading from a named pipe using a C++ ifstream.

The problem seems to be that the reading is buffered.  Does anyone know
how to set up an unbuffered ifstream in C++?  It works if I read the
named pipe using C style FILE * streams, but I would like to avoid doing
this if possible.

To demonstrate:

% gcc test_c.c -o test_c
% gcc test_cpp.cc o test_cpp
% mknod if

% ./test_c & cat -u > if
(This demonstrates that C-style FILE reading is line buffered -- OK)

% ./test_cpp & cat -u > if
(This demonstrates that C++ style ifstream reading is buffered -- how do
I get around this?)

Thanks in advance for any advice.

Josh

------------------------------------------------------------
--------------------------
test_cpp.cc (C++ ifstream)
--------------------------

#include <iostream>
#include <fstream>

using namespace std;

int main() {
  char ch;
  ifstream ain("if");
//  FILE * ain = fopen("if", "r");

  while ( true ) {
    cerr << "reading ch... ";
    ain >> ch;
//    ch=fgetc(ain);
    cerr << "got: " << ch << endl;
   }
}

-----------------
test_c.cc (C FILE)
-----------------

#include <iostream>
#include <fstream>

using namespace std;

int main() {
  char ch;
  ifstream ain("if");
//  FILE * ain = fopen("if", "r");

  while ( true ) {
    cerr << "reading ch... ";
    ain >> ch;
//    ch=fgetc(ain);
    cerr << "got: " << ch << endl;
   }
}


-- 
LinuxSA WWW: http://www.linuxsa.org.au/ IRC: #linuxsa on irc.freenode.net
To unsubscribe from the LinuxSA list:
  mail linuxsa-request at linuxsa.org.au with "unsubscribe" as the subject



More information about the linuxsa mailing list