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