Jump to content

  • Log In with Google      Sign In   
  • Create Account


C++ Binary File I/O Problem


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
4 replies to this topic

#1 mikenovemberoscar   Members   -  Reputation: 215

Like
0Likes
Like

Posted 31 July 2013 - 06:24 AM

Hi all,

 

I am trying to write binary data to a file, and I have the following C++ code:

(I borrowed the write & read functions from here)

u8 readU8(istream& file)
{
    u8 value = '\0';
    file.read((char*)value,1);
    return value;
}

void writeU8(ostream &file, u8 value)
{
    file.write((char*)value,1);
}
...
       animationFile.open("/Users/me/Desktop/BINARY_FILE.bin", ios::out | ios::binary | ios::trunc);
        
        if (!animationFile.is_open())
        {
            return 1;
        }
        
        writeU8(animationFile,u8('a'));
...

Although my program crashes and lldb returns an 'EXC_BAD_ACCESS (code = 1, address = 0x50).

 

What is wrong? If I change writeU8 to writeU16 (and the anonymous object to u16('a')):

void writeU16(ostream &file, u16 value)
{
    u8 bytes[2];
    
    // Extract the individual bytes from our value.
    
    bytes[0] = (value) & 0xFF; // Low byte
    bytes[1] = (value >> 8) & 0xFF; // High byte
    
    // Write those bytes to the file.
    
    file.write((char*)bytes,2);
}

There is no exception, but no data is written to the file.

I have also tried many different paths and filenames.

 

Thanks


Edited by mikenovemberoscar, 31 July 2013 - 06:26 AM.


Sponsor:

#2 Brother Bob   Moderators   -  Reputation: 7863

Like
0Likes
Like

Posted 31 July 2013 - 06:39 AM

write takes a pointer to the data, but value in writeU8() is the value you want to write to the file. Take the address of the value variable to get a pointer to it. The code in writeU16() appears to be correct though. How do you determine that nothing is written to the file?



#3 rip-off   Moderators   -  Reputation: 7958

Like
0Likes
Like

Posted 31 July 2013 - 07:42 AM

An array implicitly decays to a pointer to the first element. Hence the array version works, but the individual value does not.



#4 Álvaro   Crossbones+   -  Reputation: 12337

Like
0Likes
Like

Posted 31 July 2013 - 08:06 AM

EDIT: Nevermind


Edited by Álvaro, 31 July 2013 - 08:08 AM.


#5 mikenovemberoscar   Members   -  Reputation: 215

Like
0Likes
Like

Posted 31 July 2013 - 08:15 AM

Ah thankyou Brother Bob and rip-off! That fixed it. I apologise too - the reason no file was being written was I had not closed the ofstream before checking the file's size. 

Thanks again!






Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS