[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 427
  • Last Modified:

read data from binary file

Hi,
I'm very beginner if we talk about C++.
I will to know how read data from binary file from specifically position.
I was trying:
file.seekg(0,ios::beg);
file.read(memblock,size);
 and when data are in memory how can I get double data array from it?

Let say I need to read some information from the binary file.
I know that this information saved as double and starts from byte number 10.
How to do that?
I know that i VB it is like this:
        Dim a as double
        Dim IndF As Integer = FreeFile()
        FileOpen(IndF, OpenFilePath, OpenMode.Binary, OpenAccess.Read)
        FileGet(IndF, a, 10)
        FileClose(IndF)

I hope it is very easy question.
0
mastiSoft
Asked:
mastiSoft
1 Solution
 
jkrCommented:
That will depend on how 'memblock' is declared - assuming that it is a char array, you could
#define MAX_SIZE (10 * sizeof(double)) // space for 10 double values

char memblock[MAX_SIZE];

size_t size = MAX_SIZE;

file.seekg(0,ios::beg);
file.read(memblock,size);

double* pd = (double*) memblock; // cast to 'double*', can be used as an array

for (size_t i = 0; i < MAX_SIZE; ++i) {

  cout << pd[i] << endl;
}

Open in new window

0
 
JimBeveridgeCommented:
If you already have an array of double, cast to char* instead of the other way around.

double buffer[50];
file.read ((char*)buffer, sizeof(buffer));

To do it dynamically with STL vector, it would look like this:

vector<double> buf;
buf.resize(50);
file.read(&buffer[0], sizeof(double)*buf.length());
0
 
mastiSoftAuthor Commented:
Thank you. It works fine.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now