Mail Archives: djgpp/1996/09/30/20:05:28
Sorry about the long message, but this problem is somewhat complicated.
I have problems with fstream, in read/write mode, when I try to seek
in a file and read and write within one open ... close session. I have
included the source of a test program, which is documented to show the
problem.
The problem, however only exists when the program is compiled by DJGPP.
// Source code starts on this line
// This source is tested with Borland C++ and DJGPP compilers
// Is there something wrong with the fstream class in DJGPP ??
// This program below should run successfully, and produce
// the output (to cout):
// line 1a
// line 2
// line 1b
// line 2
// But instead it outputs "error 2" when compiled with DJGPP ! (see
program)
// Compiling with Borland C++ does produce the correct output.
// What's wrong? The program first writes 2 strings in binary mode,
// then re-opens the file and replaces the first string by another.
// Both times it reads the two lines in the file, to check the
// results. The tricky part is that the program seeks, read and writes
// in file while it is in read/write mode. I cannot figure out
// what the problem is. Anyone? Bug in libiostr? In gcc? Or in my
program?
// Any suggestions for code that produces the wanted result?
#include <iostream.h>
#include <string.h>
#include <fstream.h>
#include <stdio.h>
#include <stdlib.h>
#define FNAME "temp.tmp"
void error(int i) // "custom" error
{ cout << "error " << i << "\n";
exit(1);
}
int main(void)
{ fstream f;
char L1a[10]="line 1a";
char L1b[10]="line 1b";
char L2[10]= "line 2";
char S[10]= "";
remove("temp.tmp");
// THE NEXT CODE DOES THE FOLLOWING:
// - CREATE FILE AND WRITE "line 1a" AND "line 2"
// - OPEN FILE IN R/W MODE AND READ THE 2 LINES, DUMP THEM ON SCREEN
// - THEN REPLACE THE FIRST LINE "line 1a" BY "line1b"
// - THEN READ THE LINES AGAIN AND DUMP THEM ON SCREEN
f.open(FNAME, ios::out | ios::binary); // create file
f.write(L1a,strlen(L1a)+1); // write line 1a
f.write(L2,strlen(L2)+1); // write line 2
if (f.fail()) error(1); // error ?
f.close(); // close
f.open(FNAME,ios::in | ios::out | ios::nocreate | ios::binary);
f.read(S,strlen(L1a)+1); cout << S << "\n"; // reopen, read line
1a
f.read(S,strlen(L2)+1); cout << S << "\n"; // read line 2
if (f.fail()) error(2); // error ?
// --------------------------------------------
// DJGPP STOPS HERE, AND TEMP.TMP IS 0 BYTES !!
// f.open TRUNCATED THE FILE ???
// NOTE: adding ios::ate in the open function
// and do a f.seekg(0,ios::beg) to rewind
// is NOT a solution!
// --------------------------------------------
f.seekp(0,ios::beg); // back to beginning
f.write(L1b,strlen(L1b)+1); // replace line 1a by
1b
f.seekg(0,ios::beg); // back to beginning
f.read(S,strlen(L1b)+1); cout << S << "\n"; // read line 1b
f.read(S,strlen(L2)+1); cout << S << "\n"; // read line 2
if (f.fail()) error(3); // error ?
f.close(); // close
return 0;
}
// Richard van Paasen.
- Raw text -