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