简体   繁体   中英

Reading an array of integers from a binary file

I am trying to read a binary file into an array of 16-bit integers. I used a for loop to read the data and it works properly. This is how I read the file:

 int L = (End-Start)/2;;
 int16_t* I = new int16_t[L];
 int16_t s;

 for(int i=1; i<=L; i++)
 {
     inFile.read((char*)&I[i], sizeof(s));
 }
 

I was wondering if there is any way that I can read the whole array without using for loop?

Probably you do not wanted

for(int i=1; i<=L; i++)

but

for(int i=0; i<L; i++)

because the first index in an array is 0, not 1.

I was wondering if there is any way that I can read the whole array without using for loop?

you can replace:

 for(int i=0; i<L; i++) { inFile.read((char*)&I[i], sizeof(s)); }

by:

inFile.read((char*)I, sizeof(*I)*L);

If your loop reads well the integers the line above will do too, else the two ways will have the same error (for instance about the endianness).

I recommend you to not use uppercase character to start the name of a local variable and to let that for the global variables, this is a very common practice to help to read C sources.

The variable s (eg int16_t s; ) is useless so I removed it.

sizeof(*I) values the size of an element of I , that form allows to not depends on the type I point to and to stay valid even you modify it.

You can simplify the read operation to one statement:

int16_t* I = new int16_t[L];
inFile.read((char*)&I[0], L * sizeof(int16_t));

There is no need for a for loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM