Link to home
Start Free TrialLog in
Avatar of DaveStahl
DaveStahl

asked on

Can't output numerical values to a file

I am trying to output the values of an array of integer variables to a file using the following code:

ofstream outf;
outf.open(argv[4],ios::out|ios::binary);
if(outf){

      long numRecords;
      char recordType[2200];
      int val[13][2200];

               recordType[1999] = 'D';
               val[0][0] = 251658240;
               val[1][0] = 2;
               val[2][0] = 2;
               val[3][0] = 0;
               val[4][0] = 0;

               //there are additional values is this area

               recordType[1999] = 'D';
               val[0][1999] = 251658240;
               val[1][1999] = 2;
               val[2][1999] = 2;
               val[3][1999] = 0;
               val[4][1999] = 0;
               val[5][1999] = -2000;
               val[6][1999] = -4000;
               val[7][1999] = -6000;
               val[8][1999] = -8000;
               val[9][1999] = -10000;
               val[10][1999] = -12000;
               val[11][1999] = -14000;
               val[12][1999] = -16000;
               numRecords = 2000;

      for(long i = 0; i < numRecords; i++){
            outf << recordType[i] << val[0][i];
            for(int j = 1; j < 13;  j++)
                  outf << val[j][i];
      }
      outf.close();
}

But the output file ends up containing the ascii characters corresponding to these values rather than their numeric binary values.  What am I doing wrong!!!
Avatar of greggpb
greggpb

dont use the ios::binary flag
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of DaveStahl

ASKER

Thanks alot!  Actually in order to work this needed to be revised slightly to:

char* valOut = new char();
for(long i = 0; i < numRecords; i++){
     outf << recordType[i];
     for(int j = 0; j < 13; j++){
         valOut = (char*)&val[j][i];
         outf.write(valOut, sizeof(int));
     }
}

Using (char*)val[i][j] saved the VALUE at val[i][j] as a pointer which caused an access violation runtime error.  &val[i][j] gave the right value.  Also I found that in order to get it to work I needed to allocate memory for the char* with the new operator.  Just coding outf.write((char*)&val[i][j],sizeof(int)); also made it crash.  But definitely thanks for pointing me in the right direction.  I was starting to go nuts trying to figure this out.
You're most welcome :o)