Last active
April 27, 2016 07:28
-
-
Save tenomoto/2f4d422530397bb736525c9ce0fa5c0f to your computer and use it in GitHub Desktop.
Read m elements from a binary file with offset of n elements and return C++ std::vector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <fstream> | |
#include <vector> | |
template <typename T> | |
std::vector<T> read_binary(std::string fname, size_t n, size_t m, bool reverse = false, bool verbose = false) | |
{ | |
union u | |
{ | |
char c[sizeof(T)]; | |
T r; | |
}; | |
union u buf; | |
std::vector<T> data; | |
std::ifstream ifs (fname, std::ios::binary); | |
ifs.seekg(n * m * sizeof(T)); | |
if (verbose) | |
{ | |
std::cout << "pos = " << ifs.tellg() << std::endl; | |
} | |
if (ifs.is_open()) | |
{ | |
for (int j = 0; j < m; j++) | |
{ | |
ifs.read(&(buf.c[0]), sizeof(T)); | |
if (reverse) | |
{ | |
for (int i = sizeof(T) - 1; i >= 0; i--) | |
{ | |
ifs.read(&(buf.c[i]), sizeof(char)); | |
} | |
} | |
else { | |
for (int i = 0; i < sizeof(T); i++) | |
{ | |
ifs.read(&(buf.c[i]), sizeof(char)); | |
} | |
} | |
data.push_back(buf.r); | |
if (verbose) | |
{ | |
std::cout << "data(" << j << ") = " << data[j] << std::endl; | |
} | |
} | |
} | |
ifs.close(); | |
return data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment