By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,194 Members | 888 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,194 IT Pros & Developers. It's quick & easy.

Binary files, why does this code crash?

P: n/a
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::out);

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
Jul 22 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
"William Payne" <mi**************@student.liu.se> writes:
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::out); file.write(name, sizeof(name));
file.write((char*)number, sizeof(unsigned short));

&number

Jul 22 '05 #2

P: n/a

"Tim Love" <tp*@eng.cam.ac.uk> wrote in message
news:ce**********@pegasus.csx.cam.ac.uk...
"William Payne" <mi**************@student.liu.se> writes:
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::out);
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
Jul 22 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.