[Wylug-help] C++ Programming Question.

Roger Leigh rleigh at whinlatter.ukfsn.org
Tue Aug 24 21:56:59 BST 2004


Dave Whiteley <d.l.whiteley at ee.leeds.ac.uk> writes:

> We have some students sitting a resit exam tomorrow, and we have just
> been checking that the code they have beed asked to study compiles
> properly, and of course it does not.
>
> We have changed the version of cygwin's gcc (g++) that we are using since the
> original exam and the work involved in downgrading the version would
> be considerable - and so I wish to avoid it.
>
> In the code we had statements:-
>
>       infile = new ifstream(fileno(stdin));
> and
>       outfile = new ofstream(fileno(stdout));

Neither of these forms are part of the ISC C++ standard.

> These are now giving an error of
> "Cannot convert from int to char*" for arg 1 of the constructors.

That's correct.  There is no such constructor for a
std::basic_istream.

> When I look at the manual for ifstream and ofstream I find
> constructors of the form
>
>    ifstream::ifstream (int fd)
> and
>    ofstream::ofstream (int fd)
>
> as well as
>
>    ifstream::ifstream (const char* fname [, int mode [, int prot]])
>    ofstream::ofstream (const char* fname [, int mode [, int prot]])

Which manual is this.  It's certainly not in the GCC 3.3 or 3.4
manuals.

I had a look, and it's available as a GNU extension (since you are
relying on POSIX features the C++ standard does not cater for).
Here's a simple example.  Basically, you need a special streambuffer
that talks to a UNIX fd or C FILE*.  This excludes dynamic memory
allocation, which is not required to demonstrate its use, and makes
things more complex.  This uses ostreams, but it's the same idea for
istreams (but with std::ios::in).


#include <cstdio>
#include <fstream>
#include <ext/stdio_filebuf.h>

int main(void)
{
  // stream using a UNIX file descriptor
  std::ofstream os;
  __gnu_cxx::stdio_filebuf<char> fdbuf(1, std::ios::out);
  os.std::ios::rdbuf(&fdbuf);

  os << "Hello, world!" << std::endl;

  // stream using an ISO C FILE structure
  __gnu_cxx::stdio_filebuf<char> filbuf(stdout, std::ios::out);
  os.std::ios::rdbuf(&filbuf);
  os << "Goodbye!" << std::endl;

  return 0;
}


[Perhaps I should have studied programming at Uni!.  I might have
passed the exam--are the exam papers publicly available after the
day?]


Regards,
Roger

--
Roger Leigh

                Printing on GNU/Linux?  http://gimp-print.sourceforge.net/
                GPG Public Key: 0x25BFB848.  Please sign and encrypt your mail.




More information about the Wylug-help mailing list