Bitcoin ABC  0.26.3
P2P Digital Currency
readwritefile.cpp
Go to the documentation of this file.
1 // Copyright (c) 2015-2020 The Bitcoin Core developers
2 // Copyright (c) 2017 The Zcash developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #include <fs.h>
7 
8 #include <cstdio>
9 #include <limits>
10 #include <string>
11 #include <utility>
12 
13 std::pair<bool, std::string>
14 ReadBinaryFile(const fs::path &filename,
15  size_t maxsize = std::numeric_limits<size_t>::max()) {
16  FILE *f = fsbridge::fopen(filename, "rb");
17  if (f == nullptr) {
18  return std::make_pair(false, "");
19  }
20  std::string retval;
21  char buffer[128];
22  do {
23  const size_t n = fread(buffer, 1, sizeof(buffer), f);
24  // Check for reading errors so we don't return any data if we couldn't
25  // read the entire file (or up to maxsize)
26  if (ferror(f)) {
27  fclose(f);
28  return std::make_pair(false, "");
29  }
30  retval.append(buffer, buffer + n);
31  } while (!feof(f) && retval.size() <= maxsize);
32  fclose(f);
33  return std::make_pair(true, retval);
34 }
35 
36 bool WriteBinaryFile(const fs::path &filename, const std::string &data) {
37  FILE *f = fsbridge::fopen(filename, "wb");
38  if (f == nullptr) {
39  return false;
40  }
41  if (fwrite(data.data(), 1, data.size(), f) != data.size()) {
42  fclose(f);
43  return false;
44  }
45  return fclose(f) == 0;
46 }
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:30
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:28
std::pair< bool, std::string > ReadBinaryFile(const fs::path &filename, size_t maxsize=std::numeric_limits< size_t >::max())
Read full contents of a file and return them in a std::string.
bool WriteBinaryFile(const fs::path &filename, const std::string &data)
Write contents of std::string to a file.