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