Output unformatted C++ similar to FORTRAN

1

I'm looking to convert some FORTRAN code to C++. I'm having some issues around the unformatted outputs.

In FORTRAN I have some code as follows

program main
integer*4 :: one
one = 1
open(unit = temp, file = "temp.dat", status = 'replace', form='unformatted')
WRITE(temp) one, one
end

The output of this code ends up being

0x0800 0000 0100 0000 0100 0000 0800 0000 
0x0a

So to me it appears as if the output is a little bit strange. I've been playing around with it, and I think the 0x08 is for a size of the variables being written, the two 0x00000001 are for the two four byte ones being written and the 0x00000008 may be a closing size buffer (I don't know why this would be 4 bytes when the opening buffer is a single byte). The 0x00000a appears to be an EOF character.

When I try to mimic the output with C++, I do

int main(){
    long one = 1;
    std::ofstream outFile;
    outFile.open("temp.dat", std::ofstream::out)
    outFile << one << one;
    outFile.close()
}

This didn't work because it tried to write the string for 1 out instead of the binary, so then I tried:

int main(){
    long one = 1;
    std::ofstream outFile;
    outFile.open("temp.dat", std::ofstream::out) 
    outFile.write((char*) one, sizeof(one));  //Line a
    outFile.write((char*) one, sizeof(one));
    outFile.close()
}

In hopes that by casting it as a char, the direct binary would be output. Unfortunately this has a SigSev fault on line a. I'm not quite sure why.

Is an approach like this a good approach, or should I try to go in a different direction?

c++
fortran
output
ofstream
asked on Stack Overflow Apr 19, 2018 by Dave Lass

1 Answer

1

So stealing from chtz, I found a way to match the two outputs. I don't know if this is the most efficient.

int main(){
    int one = 1;
    int sizeOf = 2*sizeof(one);
    std::ofstream outFile;
    outFile.open("temp.dat", std::ofstream::out) 
    outFile.write(reinterpret_cast<const char*>(&sizeOf),sizeof(sizeOf)); 
    outFile.write(reinterpret_cast<const char*>(&one),sizeof(one));
    outFile.write(reinterpret_cast<const char*>(&one),sizeof(one));
    outFile.write(reinterpret_cast<const char*>(&sizeOf),sizeof(sizeOf));  

    outFile.close()
}
answered on Stack Overflow Apr 19, 2018 by Dave Lass

User contributions licensed under CC BY-SA 3.0