Belle II Software development
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
19using namespace Belle2;
20
21void 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
38void File::unlink(const std::string& path)
39{
40 if ((::unlink(path.c_str())) < 0) {
41 perror("unlink");
42 }
43 close();
44}
45
46size_t File::write(const void* buf, size_t count)
47{
48 size_t c = 0;
49 while (c < count) {
50 errno = 0;
51 int ret = ::write(m_fd, ((unsigned char*)buf + c), (count - c));
52 if (ret <= 0) {
53 switch (errno) {
54 case EINTR: continue;
55 case ENETUNREACH:
56 case EHOSTUNREACH:
57 case ETIMEDOUT:
58 usleep(500);
59 continue;
60 default:
61 throw (IOException("Error while writing"));
62 }
63 }
64 c += ret;
65 }
66 return c;
67}
68
69size_t File::read(void* buf, size_t count)
70{
71 size_t c = 0;
72 while (c < count) {
73 errno = 0;
74 int ret = ::read(m_fd, ((unsigned char*)buf + c), (count - c));
75 if (ret <= 0) {
76 switch (errno) {
77 case EINTR: continue;
78 case EAGAIN: continue;
79 default:
80 throw (IOException("Error while reading. %d", errno));
81 }
82 }
83 c += ret;
84 }
85 return c;
86}
87
88bool File::exist(const std::string& filename)
89{
90 struct stat st;
91 if (stat(filename.c_str(), &st) != 0) {
92 return false;
93 } else {
94 mode_t m = st.st_mode;
95 if (S_ISDIR(m)) {
96 return false;
97 } else {
98 return true;
99 }
100 }
101 return false;
102}
Abstract base class for different kinds of events.