"Dr. Len" <le*@wohoo.org> wrote in message news:gc********************************@4ax.com...
Hi all!
Given that I have a binary file which contains 4-byte integer values
in sequence and I know in advance how many there are, does the C++
standard have any algorithm or like method to read them into a
std::vector container with a single command? Right now I'm using a
temporary variable and push_back(), but this is bit clumsy way IMO:
int tmp;
std::vector<int> someVector;
std::ifstream in("somefile", std::ios_base::in |
std::ios_base::binary);
for(int i = 0; i < count; i++)
{
in.read((char*)&tmp, 4);
someVector.push_back(tmp);
}
------ file2vect.cpp : BEGIN ------
#include <cstdio>
#include <cassert>
#include <vector>
#include <iostream>
#include <iterator>
#include <fstream>
using namespace std;
vector<int> read_file_to_vector(const char* const filename_i)
{
ifstream f(filename_i, ios_base::binary);
assert (f);
istream_iterator<int> b(f), e;
const vector<int> v (b, e);
return v;
}
void create_test_infile (const char* const filename_i)
{
::remove (filename_i);
ofstream outfile (filename_i, ios_base::binary);
assert (outfile);
outfile << 1234 << " " << 5678 << " " << 9012 << endl;
}
int main ()
{
#define INFILE_NAME "foo.in"
create_test_infile (INFILE_NAME);
const vector<int> v (read_file_to_vector (INFILE_NAME));
// ------ Show ------
ifstream infile(INFILE_NAME, ios_base::binary);
assert (infile);
cout << "File : ";
cout << infile.rdbuf();
cout << "Vector : ";
copy (v.begin(), v.end(), ostream_iterator<int> (cout, " "));
cout << endl;
// ------------------
return 0;
}
------ file2vect.cpp : END --------
--
Alex Vinokur
http://mathforum.org/library/view/10978.html http://sourceforge.net/users/alexvn