To: djgpp AT sun DOT soe DOT clarkson DOT edu From: "Lenny A. Krieg" Date: 26 Mar 93 13:31:49 ET Subject: Writing Binary Files There seems to be a problem writing BINARY files. I have included three simple programs [PROGRAM 1, PROGRAM 2, and PROGRAM 3]. The first program, PROGRAM 1, opens a BINARY file using FOPEN and writes out 1600 unsigned ASCII 255 values. It works fine. The second program, PROGRAM 2, opens a BINARY file using OFSTREAM and attempts to write out 1600 unsigned ASCII 255 values. The file produced is empty. The third program, PROGRAM 3, opens a BINARY file using OFSTREAM and attempts to write out 1600 unsigned ASCII 254 values. It works fine. Am I doing something wrong or is there a problem with writing BINARY files that contain ASCII 255? What is magical about ASCII 255? Does anyone know a solution using OFSTREAM? ------------------- PROGRAM 1 -------------------------------- #include #include int main ( ) { FILE * fp; if ( ( fp = fopen ( "FILE1", "wb" ) ) == NULL ) exit ( 1 ); int * data; int width = 40; int height = 40; if ( ! ( data = new int [ width * height ] ) ) exit ( 2 ); int k; for ( k = 0; k < width * height; k++ ) data [ k ] = 255; for ( k = 0; k < width * height; k++ ) fputc ( ( unsigned char ) data [ k ], fp ); return ( 0 ); } ------------------- PROGRAM 2 -------------------------------- #include #include <_string.h> #include #include int main ( ) { FILE * fp; ofstream binfile ( "FILE2", ios::out|ios::binary|ios::trunc ); if ( ! binfile ) exit ( 2 ); int * data; int width = 40; int height = 40; if ( ! ( data = new int [ width * height ] ) ) exit ( 2 ); int k; for ( k = 0; k < width * height; k++ ) data [ k ] = 255; for ( k = 0; k < width * height; k++ ) binfile << ( unsigned char ) data [ k ]; return ( 0 ); } ------------------- PROGRAM 3 -------------------------------- #include #include <_string.h> #include #include int main ( ) { FILE * fp; ofstream binfile ( "FILE3", ios::out|ios::binary|ios::trunc ); if ( ! binfile ) exit ( 2 ); int * data; int width = 40; int height = 40; if ( ! ( data = new int [ width * height ] ) ) exit ( 2 ); int k; for ( k = 0; k < width * height; k++ ) data [ k ] = 254; for ( k = 0; k < width * height; k++ ) binfile << ( unsigned char ) data [ k ]; return ( 0 ); } ------------------- END --------------------------------------