Reputation: 5193
Why is everything being read as 0?
int width = 5;
int height = 5;
int someTile = 1;
char buff[128];
ifstream file("test.txt", ios::in|ios::binary);
if(file.is_open())
{
cout << "open";
}
file.read(buff, sizeof(int));
width = atoi(buff);
file.read(buff, sizeof(int));
height = atoi(buff);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
file.read(buff, sizeof(int));
someTile = atoi(buff);
cout << someTile;
}
}
My file format code is in C# and written like this:
FileStream stream = new FileStream("test.txt", FileMode.Create);
BinaryWriter writer = new BinaryWriter(stream);
// write a line of text to the file
writer.Write(15);
writer.Write(5);
for (int i = 0; i < 15; i++)
{
for (int j = 0; j < 5; j++)
{
writer.Write(1);
}
}
// close the stream
writer.Close();
Upvotes: 0
Views: 1479
Reputation: 11608
Without knowing the contents of test.txt it's difficult to say exactly, but it looks like you're repeatedly reading 4 bytes (size of an int on most platforms) into a character buffer / string, and then trying to turn that into a number. Unless your file is constructed entirely of four byte blocks that are null-terminated, I wouldn't expect this to work.
Update: Ok, looking at your file format you're not writing strings, you're writing ints. Therefore I'd expect you to be able to read your numbers straight back in, with no need for atoi
.
For example:
int value;
file.read((char*)&value, sizeof(int));
value
should now contain the number from the file. To convert your whole example you're looking for something like this:
int width = 5;
int height = 5;
int someTile = 1;
ifstream file("test.txt", ios::in|ios::binary);
if(file.is_open())
{
cout << "open";
file.read(reinterpret_cast<char*>(&width), sizeof(int));
file.read(reinterpret_cast<char*>(&height), sizeof(int));
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
file.read(reinterpret_cast<char*>(&someTime), sizeof(int));
cout << someTile;
}
}
}
Upvotes: 1
Reputation: 33655
atoi
converts a NUL terminated string to an integer - you are reading four bytes from the file (it's in binary mode) - which may not be correct..
for example, a valid string (for atoi
to work could be, "1234" - NOTE: NUL terminated), however the byte representation of this is 0x31 0x32 0x33 0x34 (note NUL terminated given you only read 4 bytes, so, atoi
could be doing anything). What is the format of this file? If it really is byte representation, the number 1234 would look like (depending on endianess), 0x00 0x00 0x04 0xD2, the way to correctly read this int
would be to shift in byte by byte.
So, big question - what is the format?
Upvotes: 0