Bitcoin Core 31.99.0
P2P Digital Currency
readwritefile.cpp
Go to the documentation of this file.
1// Copyright (c) 2015-present 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
7
8#include <util/fs.h>
9
10#include <algorithm>
11#include <cstdio>
12#include <string>
13#include <utility>
14
15std::pair<bool,std::string> ReadBinaryFile(const fs::path &filename, size_t maxsize)
16{
17 FILE *f = fsbridge::fopen(filename, "rb");
18 if (f == nullptr)
19 return std::make_pair(false,"");
20 std::string retval;
21 char buffer[128];
22 do {
23 const size_t n = fread(buffer, 1, std::min(sizeof(buffer), maxsize - retval.size()), 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
36bool WriteBinaryFile(const fs::path &filename, const std::string &data)
37{
38 FILE *f = fsbridge::fopen(filename, "wb");
39 if (f == nullptr)
40 return false;
41 if (fwrite(data.data(), 1, data.size(), f) != data.size()) {
42 fclose(f);
43 return false;
44 }
45 if (fclose(f) != 0) {
46 return false;
47 }
48 return true;
49}
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:23
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)
Read full contents of a file and return them in a std::string.