File: io.hh

package info (click to toggle)
last-align 1609-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 14,656 kB
  • sloc: cpp: 44,297; python: 5,192; ansic: 1,937; sh: 651; makefile: 457
file content (38 lines) | stat: -rw-r--r-- 1,027 bytes parent folder | download | duplicates (5)
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
// Copyright 2008, 2009, 2010 Martin C. Frith

#ifndef IO_HH
#define IO_HH

#include <string>
#include <stdexcept>
#include <fstream>
#include <cassert>

namespace cbrc{

template<typename T>  // T should be a vector-iterator or a pointer
void memoryToStream( T beg, T end, std::ostream& s ){
  assert( beg < end );
  enum { CHUNK_SIZE = 1073741824 };  // need to do big writes in chunks: why?
  const char * b = (const char*)&(*beg);
  const char * e = (const char*)&(*end);
  while( e - b > CHUNK_SIZE ){
    s.write( b, CHUNK_SIZE );
    b += CHUNK_SIZE;
  }
  s.write( b, e - b );
}

template<typename T>  // T should be a vector-iterator or a pointer
void memoryToBinaryFile( T beg, T end, const std::string& fileName ){
  if( beg == end ) return;
  std::ofstream file( fileName.c_str(), std::ios::binary );
  if( !file ) throw std::runtime_error( "can't open file: " + fileName );
  memoryToStream( beg, end, file );
  file.close();
  if( !file ) throw std::runtime_error( "can't write file: " + fileName );
}

}

#endif