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: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
#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: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