Beginner's question about matrices

I ultimately need to read in a binary file of unsigned ints into a matrix. The goal is to manipulate this matrix and extract a submatrix. (The binary is a 3D image and I want to make a separate file with some arbitrary chunk of the image)

I first read the file into a memory block and now I want to put this into the matrix (210x210x1000).

Is it possible to use the std::vector? Do I need to use a for loop and fill each matrix element, parsing the memory block by the size of an unsigned int?


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

#include <iostream>
#include <fstream>
#include <stdio.h>

#include <cstdlib>
#include <ctime>
#include <unistd.h>
#include <string>
#include <vector>

void test() {

  // parameters from header, hardcoded for now
  int row = 210;
  int col = 210;


  string filename = "130521-full-ATN.i33";


  ifstream::pos_type size; 
  char *memblock; 


  ifstream infile(filename.c_str(), ios::in|ios::binary|ios::ate); 
  if (infile.is_open()) 
    { 


      size = infile.tellg(); 
      memblock = new char [size]; 
      infile.seekg (0, ios::beg); 
      infile.read(memblock, size); 
      infile.close();  
      cout << "File is in memory\n"; 

      ofstream outfile ("test.i33", ios::out|ios::binary);
      outfile.write(memblock,size);
      outfile.close();

      delete[] memblock; 
    } 
  else cout << "Unable to open file";

}

Is it possible to use the std::vector?
Yes

Do I need to use a for loop and fill each matrix element, parsing the memory block by the size of an unsigned int?
No.

It depends on the format of the data in the file. If the file is a sequence of int's, written by the same kind of computer, you can read the block as you're doing now. You'll need to set the size of the vector before the read.
1
2
3
4
std::vector<int> block;
//... get size of file and open file
block.resize(size/sizeof(int));
infile.read(&v[0], size);


Now, that's equivalent to what you've done with the memblock.
Last edited on
I get this error when I try to assign it to block:

Error: Can't call basic_ifstream<char,char_traits<char> >::read(&block[0],size) in current scope test.C:51:
Possible candidates are...
public: basic_istream<char,char_traits<char> >::__istream_type& basic_istream<char,char_traits<char> >::read(basic_istream<char,char_traits<char> >::char_type* s,streamsize n);
v[0] is an int.
&v[0] is an int*
You need static_cast<char*>(&v[0]) as read is expecting a pointer to a byte.
Last edited on
Topic archived. No new replies allowed.