delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1993/03/26/14:29:00

To: djgpp AT sun DOT soe DOT clarkson DOT edu
From: "Lenny A. Krieg" <LKRIEG AT dpc2 DOT hdos DOT hac DOT com>
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 <stdio.h>
#include <builtin.h>

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 <fstream.h>
#include <_string.h>
#include <stdio.h>
#include <builtin.h>

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 <fstream.h>
#include <_string.h>
#include <stdio.h>
#include <builtin.h>

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 --------------------------------------


- Raw text -


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