I have written a binary file using a struct as follows:
struct block{
char data[32];
};
so what I end up with is basically a large binary file full of char[32]. The data is formatted in specific positions so grabbing specific pieces of information is not difficult. However, I tried to read the file like so:
int lines=0;
std::ifstream inputFile("file.bin",std::ios::binary);
while (!inputFile.eof())
{
inputFile.read(blocks[lines].data, sizeof(block));
lines++;
}
inputFile.close();
lines--;
and then displaying it like this:
std::cout<<"block 1: "<<blocks[0].data<<std::endl;
// etc ...
I thought that blocks[i].data should just give me the char[32] that belongs to index i, but it instead gives me every “data” element in the struct from that index to the end of the struct. I’m sure that it is my misunderstanding of how that works. My question is: how do I just get the char[32] represented by blocks[i].data?
The problem is your
std::coutoutput statement. When you try to outputblocks[0].data, whatoperator<<gets is not the array of 32 chars, but a pointer to the first char. This is interpreted as pointer to a C string, and therefore it outputs all characters found in memory from there on until it finds a'\0'. Since each array element contains just the corresponding characters from the file, all characters of the file are output (unless there’s a'\0'in the file, then output stops there). Also, you seem to be (un-)lucky that a'\0'follows your data in memory, so the output stops there (instead of continuing to output whatever is in memory afterwards, and possibly giving a segmentation fault when the end of the process’ memory is reached).To just output the 32 charactes as characters, use
std::cout.write(blocks[0].data,32). Otherwise to output them as ints just loop through them and convert each one to int:Of course you can use all the stream manipulators to get the numbers in the form you want (e.g.
std::hexfor hexadecimal output, and/orstd::setwandstd::setfillto get fixed width numbers).