Binary files, why does this code crash?

W

William Payne

Hello! Consider the following code:

#include <fstream>
#include <iostream>

int main()
{
char name[256] = {"testing"};
unsigned short number = 4711;

std::fstream file("foo.dat", std::ios_base::binary | std::ios_base::eek:ut);

file.write(name, sizeof(name));
file.write((char*)number, sizeof(unsigned short));

file.close();

file.open("foo.dat", std::ios_base::binary | std::ios_base::in);

char name2[256];
unsigned short number2 = 0;

file.read(name2, sizeof(name2));
file.read((char*)&number2, sizeof(unsigned short));

file.close();

std::cout << "name2 = " << name2 << std::endl;
std::cout << "number2 = " << number2 << std::endl;
}

This program ends with a segmentation fault when I run it. It seems to
create the file foo.dat, but it appears to be completely empty. No output is
shown on the screen. What am I doing wrong here?

Oh, and one more thing. My compiler issues the following warning about this
line:
file.write((char*)number, sizeof(unsigned short));
binary_file.cpp:12: warning: cast to pointer from integer of different size

Is it safe to ignore this warning or is it part of the problem with the
code? When I program I like to crank up the warning level of the compiler to
the max and fix all warnings so I'd like to get rid of it even if it's
harmless in this case.

Thanks for any replies

/ WP
 
W

William Payne

Tim Love said:
William Payne said:
Hello! Consider the following code:
#include <fstream>
#include <iostream>
int main()
{
char name[256] = {"testing"};
unsigned short number = 4711;
std::fstream file("foo.dat", std::ios_base::binary |
std::ios_base::eek:ut);
file.write(name, sizeof(name));
file.write((char*)number, sizeof(unsigned short));
&number

Doh, what a stupid mistake! Thanks alot for spotting it, Tim!

/ WP
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top