hmbdc
simplify-high-performance-messaging-programming
DownloadFile.hpp
1 #include "hmbdc/Copyright.hpp"
2 #pragma once
3 
4 #include <fstream>
5 #include <limits>
6 #include <stdint.h>
7 #include <unistd.h>
8 #include <fcntl.h>
9 
10 
11 namespace hmbdc { namespace os {
12 struct DownloadFile {
13  DownloadFile()
14  : fd_(-1)
15  , fullLen_(0)
16  , len_(0) {
17  }
18 
19  bool open(char const* dir, char const* filenamePreferred
20  , size_t len = std::numeric_limits<size_t>::max()) {
21  std::string fullPath = std::string(dir) + "/" + std::string(filenamePreferred);
22  actualName_ = fullPath;
23  int postfix = 1;
24 
25  do {
26  fd_ = ::open(actualName_.c_str(), O_WRONLY | O_CREAT | O_EXCL
27  , S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
28  if (fd_ != -1) {
29  fullLen_ = len;
30  len_ = 0;
31  return true;
32  } else {
33  actualName_ = fullPath + " (" + std::to_string(++postfix) + ")";
34  }
35  } while(postfix < 256);
36  return false;
37  }
38 
39  explicit operator bool() const {
40  return fd_ != -1;
41  }
42 
43  bool writeDone() const {
44  return fullLen_ == len_;
45  }
46 
47  size_t write(void const* mem, size_t l) {
48  auto wl = std::min(l, fullLen_ - len_);
49  auto res = wl;
50  if (fd_ != -1) {
51  res = ::write(fd_, mem, wl);
52  }
53  if (res > 0) len_ += res;
54  return res;
55  }
56 
57  void close() {
58  ::close(fd_);
59  fd_ = -1;
60  }
61 
62  char const* name() const {
63  return actualName_.c_str();
64  }
65 
66  size_t fullLen() const {
67  return fullLen_;
68  }
69 
70 private:
71  int fd_;
72  std::string actualName_;
73  size_t fullLen_;
74  size_t len_;
75 
76 };
77 
78 }}
Definition: DownloadFile.hpp:12
Definition: Base.hpp:12