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  using namespace std;
22  string fullPath = string(dir) + "/" + string(filenamePreferred);
23  actualName_ = fullPath;
24  int postfix = 1;
25 
26  do {
27  fd_ = ::open(actualName_.c_str(), O_WRONLY | O_CREAT | O_EXCL
28  , S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
29  if (fd_ != -1) {
30  fullLen_ = len;
31  len_ = 0;
32  return true;
33  } else {
34  actualName_ = fullPath + " (" + to_string(++postfix) + ")";
35  }
36  } while(postfix < 256);
37  return false;
38  }
39 
40  explicit operator bool() const {
41  return fd_ != -1;
42  }
43 
44  bool writeDone() const {
45  return fullLen_ == len_;
46  }
47 
48  size_t write(void const* mem, size_t l) {
49  auto wl = std::min(l, fullLen_ - len_);
50  auto res = wl;
51  if (fd_ != -1) {
52  res = ::write(fd_, mem, wl);
53  }
54  if (res > 0) len_ += res;
55  return res;
56  }
57 
58  void close() {
59  ::close(fd_);
60  fd_ = -1;
61  }
62 
63  char const* name() const {
64  return actualName_.c_str();
65  }
66 
67  size_t fullLen() const {
68  return fullLen_;
69  }
70 
71 private:
72  int fd_;
73  std::string actualName_;
74  size_t fullLen_;
75  size_t len_;
76 
77 };
78 
79 }}
Definition: DownloadFile.hpp:12
Definition: TypedString.hpp:84
Definition: Base.hpp:12