openCARP
Doxygen code documentation for the open cardiac electrophysiology simulator openCARP
SF_io_base.h
Go to the documentation of this file.
1 #ifndef _SF_IO_BASE
2 #define _SF_IO_BASE
3 
4 #if __BYTE_ORDER == __LITTLE_ENDIAN
5 #define htobe(x) SF::byte_swap(x)
6 #define betoh(x) SF::byte_swap(x)
7 #define htole(x) (x)
8 #define letoh(x) (x)
9 #define MT_ENDIANNESS 0
10 #else
11 #define htobe(x) (x)
12 #define betoh(x) (x)
13 #define htole(x) SF::byte_swap(x)
14 #define letoh(x) SF::byte_swap(x)
15 #define MT_ENDIANNESS 1
16 #endif
17 
18 namespace SF {
19 
21 template<typename T>
22 T byte_swap(T in)
23 {
24  T out; // output buffer
25 
26  char* inp = ( char* ) (& in );
27  char* outp = ( char* ) (& out);
28  size_t size = sizeof(T);
29 
30  switch(size)
31  {
32  case 4:
33  outp[0] = inp[3];
34  outp[1] = inp[2];
35  outp[2] = inp[1];
36  outp[3] = inp[0];
37  break;
38 
39  case 2:
40  outp[0] = inp[1];
41  outp[1] = inp[0];
42  break;
43 
44  case 8:
45  outp[0] = inp[7], outp[1] = inp[6];
46  outp[2] = inp[5], outp[3] = inp[4];
47  outp[4] = inp[3], outp[5] = inp[2];
48  outp[6] = inp[1], outp[7] = inp[0];
49  break;
50 
51  default:
52  for(size_t i=0; i<size; i++)
53  outp[i] = inp[size-1-i];
54  }
55 
56  return out;
57 }
58 
66 inline bool fileExists(std::string filename)
67 {
68  return (access(filename.c_str(), F_OK) == 0);
69 }
70 
72 inline size_t file_size(FILE* fd)
73 {
74  size_t oldpos = ftell(fd);
75  fseek(fd, 0L, SEEK_END);
76  size_t sz = ftell(fd);
77  fseek(fd, oldpos, SEEK_SET);
78 
79  return sz;
80 }
81 
83 inline void treat_file_open_error(const char* file, const char* caller,
84  const int errnum, const bool do_exit, int rank)
85 {
86  if(rank == 0)
87  fprintf(stderr, "%s: IO error occured when opening file %s.\n%s\n\n", caller, file,
88  strerror(errnum));
89 
90  if(do_exit) {
91  MPI_Finalize();
92  exit(EXIT_FAILURE);
93  }
94 }
95 
96 }
97 
98 #endif
Definition: dense_mat.hpp:34
T byte_swap(T in)
swap the bytes of int, float, doubles, etc..
Definition: SF_io_base.h:22
size_t file_size(FILE *fd)
return file size from a file descriptor
Definition: SF_io_base.h:72
bool fileExists(std::string filename)
Function which checks if a given file exists.
Definition: SF_io_base.h:66
void treat_file_open_error(const char *file, const char *caller, const int errnum, const bool do_exit, int rank)
treat a file open error by displaying the errnum string interpretation and the caller ...
Definition: SF_io_base.h:83