File I/O: Extracting Buffer Contents

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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/* 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

1
2
3
4
struct DataStruct {
  unsigned long long ids; // 8 bytes
  double amount; // 8 bytes
};



I hope you can help me, I'm a real beginner in C++. Thanks in advance!
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;
    }


[EDIT]
I've changed the dsarray[0] to dsarray[i].
Last edited on
Thank you very much!
This code worked perfectly!
Topic archived. No new replies allowed.