delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/06/16/09:14:59

Message-Id: <m0ylvHt-0003CPC@fwd04.btx.dtag.de>
Date: Tue, 16 Jun 1998 14:56:33 +0200
To: djgpp AT delorie DOT com
Subject: ios::binary error, and how to repair
MIME-Version: 1.0
From: Breymann AT t-online DOT de (Breymann)

Hi,

There is an error in fstream, if ios::binary is used.
Examples:

1. DOES NOT WORK:

#include<fstream>

int main()
{
  ofstream aus("test.dat", ios::binary);
  for(int i=0; i< 15; ++i)
    aus.write((char*)&i, sizeof(int));
  aus.close();

  ifstream ein("test.dat", ios::binary);
  int i;
  while(!ein.eof()) {
    ein.read((char*)&i, sizeof(int));
    if(!ein.eof()) cout << i << endl;
  }
}

2. DOES WORK:

#include<fstream>

int main()
{
  ofstream aus("test.dat", ios::out | ios::binary);  // !!!
  for(int i=0; i< 15; ++i)
    aus.write((char*)&i, sizeof(int));
  aus.close();

  ifstream ein("test.dat", ios::in | ios::binary);  // !!!
  int i;
  while(!ein.eof()) {
    ein.read((char*)&i, sizeof(int));
    if(!ein.eof()) cout << i << endl;
  }
}

REASON: In fstream the open-mode is erroneously overwritten.

HOW TO REPAIR:
In fstream(.h) make the followingen changes:

Please comment the 3 lines after #define _FSTREAM_H as follows:

#ifndef _FSTREAM_H
#define _FSTREAM_H
//#ifdef __GNUG__             !!
//#pragma interface           !!
//#endif                      !!
#include <iostream.h>


In fstream, classes ifstream and ofstream, change 'mode'
 to 'mode | ios::in' resp. ios::out as follows:

class ifstream : public fstreambase, public istream {
  public:
    ifstream() : fstreambase() { }
    ifstream(int fd) : fstreambase(fd) { }
    ifstream(int fd, char *p, int l) : fstreambase(fd, p, l) { } /*Deprecated*/
    ifstream(const char *name, int mode=ios::in, int prot=0664)
//  : fstreambase(name, mode, prot) { }                  WRONG
  : fstreambase(name, mode | ios::in, prot) { }       // CORRECT
    void open(const char *name, int mode=ios::in, int prot=0664)
//  { fstreambase::open(name, mode, prot); }              WRONG
  { fstreambase::open(name, mode | ios::in, prot); }   // CORRECT
};

class ofstream : public fstreambase, public ostream {
  public:
    ofstream() : fstreambase() { }
    ofstream(int fd) : fstreambase(fd) { }
    ofstream(int fd, char *p, int l) : fstreambase(fd, p, l) { } /*Deprecated*/
    ofstream(const char *name, int mode=ios::out, int prot=0664)
//  : fstreambase(name, mode, prot) { }                 WRONG!
  : fstreambase(name, mode | ios::out, prot) { }     // CORRECT
    void open(const char *name, int mode=ios::out, int prot=0664)
//  { fstreambase::open(name, mode, prot); }   falsch!  WRONG!
  { fstreambase::open(name, mode | ios::out, prot); }  // CORRECT
};

The error was known already in GNU 2.7.2, but my message probably got
lost.

Best regards


    Uli


- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019