Belle II Software  release-05-02-19
File.cc
1 #include "daq/slc/system/File.h"
2 
3 #include <daq/slc/base/IOException.h>
4 
5 #include <unistd.h>
6 #include <sys/stat.h>
7 #include <fcntl.h>
8 #include <errno.h>
9 
10 #include <cstdio>
11 
12 using namespace Belle2;
13 
14 void File::open(const std::string& path, const std::string& mode_s)
15 {
16  int mode = O_RDONLY;
17  if (mode_s.find("w") != std::string::npos) {
18  mode = O_WRONLY;
19  if (mode_s.find("r") != std::string::npos) {
20  mode = O_RDWR;
21  } else {
22  mode |= O_CREAT;
23  }
24  }
25  if ((m_fd = ::open(path.c_str(), mode, 0666)) < 0) {
26  perror("open");
27  throw (IOException("Failed to open file : %s", path.c_str()));
28  }
29 }
30 
31 void File::unlink(const std::string& path)
32 {
33  if ((::unlink(path.c_str())) < 0) {
34  perror("unlink");
35  }
36  close();
37 }
38 
39 size_t File::write(const void* buf, size_t count)
40 {
41  size_t c = 0;
42  int ret;
43  while (c < count) {
44  errno = 0;
45  ret = ::write(m_fd, ((unsigned char*)buf + c), (count - c));
46  if (ret <= 0) {
47  switch (errno) {
48  case EINTR: continue;
49  case ENETUNREACH:
50  case EHOSTUNREACH:
51  case ETIMEDOUT:
52  usleep(500);
53  continue;
54  default:
55  throw (IOException("Error while writing"));
56  }
57  }
58  c += ret;
59  }
60  return c;
61 }
62 
63 size_t File::read(void* buf, size_t count)
64 {
65  size_t c = 0;
66  int ret;
67  while (c < count) {
68  errno = 0;
69  ret = ::read(m_fd, ((unsigned char*)buf + c), (count - c));
70  if (ret <= 0) {
71  switch (errno) {
72  case EINTR: continue;
73  case EAGAIN: continue;
74  default:
75  throw (IOException("Error while reading. %d", errno));
76  }
77  }
78  c += ret;
79  }
80  return c;
81 }
82 
83 bool File::exist(const std::string& filename)
84 {
85  struct stat st;
86  if (stat(filename.c_str(), &st) != 0) {
87  return false;
88  } else {
89  mode_t m = st.st_mode;
90  if (S_ISDIR(m)) {
91  return false;
92  } else {
93  return true;
94  }
95  }
96  return false;
97 }
Belle2::IOException
Definition: IOException.h:12
Belle2
Abstract base class for different kinds of events.
Definition: MillepedeAlgorithm.h:19
alignment.constraints_generator.filename
filename
File name.
Definition: constraints_generator.py:224