Bitcoin Core  24.99.0
P2P Digital Currency
readwritefile.cpp
Go to the documentation of this file.
1 // Copyright (c) 2015-2022 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 <algorithm>
9 #include <cstdio>
10 #include <limits>
11 #include <string>
12 #include <utility>
13 
14 std::pair<bool,std::string> ReadBinaryFile(const fs::path &filename, size_t maxsize=std::numeric_limits<size_t>::max())
15 {
16  FILE *f = fsbridge::fopen(filename, "rb");
17  if (f == nullptr)
18  return std::make_pair(false,"");
19  std::string retval;
20  char buffer[128];
21  do {
22  const size_t n = fread(buffer, 1, std::min(sizeof(buffer), maxsize - retval.size()), f);
23  // Check for reading errors so we don't return any data if we couldn't
24  // read the entire file (or up to maxsize)
25  if (ferror(f)) {
26  fclose(f);
27  return std::make_pair(false,"");
28  }
29  retval.append(buffer, buffer+n);
30  } while (!feof(f) && retval.size() < maxsize);
31  fclose(f);
32  return std::make_pair(true,retval);
33 }
34 
35 bool WriteBinaryFile(const fs::path &filename, const std::string &data)
36 {
37  FILE *f = fsbridge::fopen(filename, "wb");
38  if (f == nullptr)
39  return false;
40  if (fwrite(data.data(), 1, data.size(), f) != data.size()) {
41  fclose(f);
42  return false;
43  }
44  if (fclose(f) != 0) {
45  return false;
46  }
47  return true;
48 }
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:31
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:25
bool WriteBinaryFile(const fs::path &filename, const std::string &data)
Write contents of std::string to a file.
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.