Random access of Binary file contents

Hello Everyone,

I need to extract the file contents from a specified index and specified size. I have this code that is currently working:

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
36
37
38
39
40
41
42
43
44
45
46
47
48


/* fread example: read a complete file */
#include <stdio.h>
#include <stdlib.h>

struct DataStruct {
  unsigned long long ids; // 8 bytes
  double amount; // 8 bytes
};


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. */
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;
}

// terminate
fclose (pFile);
free (buffer);
return 0;
}


The current code reads the whole file, puts the whole contents to the memory, then prints each content.

My target is to read the file partially (per 61440 Bytes), then put the partial contents to memory. Then print to the screen. Then return to the file in the last index. For example, after the 1st partial read of 61440 bytes, the file pointer should be in the 61441st byte.

I hope you can give me ideas on how to implement this.

Thank you very much in advance.
Last edited on
Topic archived. No new replies allowed.