Hi, I hope you can help me with my problem. I got this code from http://www.cplusplus.com/reference/c.../cstdio/fread/. Now after the file contents have been loaded to the memory buffer (in the part /* the whole file is now loaded in the memory buffer. */), how can I extract those contents from the memory buffer and print them on the screen or do some processing on these data?
/* fread example: read a complete file */
#include <stdio.h>
#include <stdlib.h>
int main () {
FILE * pFile;
long lSize;
char * buffer;
size_t result;
pFile = fopen ( "myfile.bin" , "rb" );
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
// allocate memory to contain the whole file:
buffer = (char*) malloc (sizeof(char)*lSize);
if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
// copy the file into the buffer:
result = fread (buffer,1,lSize,pFile);
if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
/* the whole file is now loaded in the memory buffer. */
// CLUELESS ON WHAT TO DO HERE
// terminate
fclose (pFile);
free (buffer);
return 0;
}
The code above reads my binary file with a defined structure.
I want to get each records and process like this (this is other implementation, but it doesn't read the file into a memory buffer):
1 2 3 4 5 6 7
ifstream fin(binFile, ios::in | ios::binary);
for (int i=0; i < noOfRecords; i++) {
//cout << "*********************** record " << i << endl;
fin.read((char *) &mydata[i], sizeof(DataStruct));
// compute, process each record
processIt(mydata[i].ids, mydata[i].amount);
}
where
mydata is: DataStruct mydata[10]; // 10 records
and
DataStruct is
This looks like C rather than C++. The principle is the same though, I'll give a C++ solution.
You have an array of DataStruct's in memory, pointed to by buffer. But buffer is declared to be a pointer to a char. We have to override this and treat it as a pointer to an array of DataStruct's, then we can access them.
The next bit is how many DataStruct's are in the array? Enough to take lSize bytes.
1 2 3 4 5 6 7
DataStruct* dsarray = reinterpret_cast<DataStruct*>(buffer);
size_t dssize = lSize / sizeof(DataStruct);
for (size_t i = 0; i < dssize; ++i)
{
std::cout << dsarray[i].ids << '\t' << dsarray[i].amount << std::endl;
}