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