Search code examples
juliabinaryfiles

Reading a large structured binary file in Julia


I have a large binary file containing identical records with this memory layout:

# Julia code
struct Event
    ia::Int32
    ig::Int32
    Eg::Float64
    Tg::Float64
    xn::Float64
    yn::Float64
    zn::Float64

    # uninitialized constructor
    Event() = new()
end

How can I translate this C++ code in Julia?

// C++ code
struct Event
{
  int32_t ia;  
  int32_t ig;  
  double  Eg; 
  double  Tg;
  double  xn; 
  double  yn;
  double  zn;
};

// ... compute event_count

std::ifstream in(filename,std::ifstream::binary);
std::vector<Event> array(event_count);

in.read((char*)array.data(), event_count*sizeof(Event)); // <- Julia way: how to?

Solution

  • you can use read(filename, Event, n), where n is number of elements you want to read (size of target vector). Actually n can be e.g. a tuple giving dimensions of the output array.

    You can check out help of read function for other options.