/tmp/bitcoin/src/util/readwritefile.cpp
Line | Count | Source |
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 | | |
6 | | #include <util/readwritefile.h> |
7 | | |
8 | | #include <util/fs.h> |
9 | | |
10 | | #include <algorithm> |
11 | | #include <cstdio> |
12 | | #include <string> |
13 | | #include <utility> |
14 | | |
15 | | std::pair<bool,std::string> ReadBinaryFile(const fs::path &filename, size_t maxsize) |
16 | 21 | { |
17 | 21 | FILE *f = fsbridge::fopen(filename, "rb"); |
18 | 21 | if (f == nullptr) |
19 | 6 | return std::make_pair(false,""); |
20 | 15 | std::string retval; |
21 | 15 | char buffer[128]; |
22 | 47 | do { |
23 | 47 | 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 | 47 | if (ferror(f)) { |
27 | 0 | fclose(f); |
28 | 0 | return std::make_pair(false,""); |
29 | 0 | } |
30 | 47 | retval.append(buffer, buffer+n); |
31 | 47 | } while (!feof(f) && retval.size() < maxsize); |
32 | 15 | fclose(f); |
33 | 15 | return std::make_pair(true,retval); |
34 | 15 | } |
35 | | |
36 | | bool WriteBinaryFile(const fs::path &filename, const std::string &data) |
37 | 10 | { |
38 | 10 | FILE *f = fsbridge::fopen(filename, "wb"); |
39 | 10 | if (f == nullptr) |
40 | 0 | return false; |
41 | 10 | if (fwrite(data.data(), 1, data.size(), f) != data.size()) { |
42 | 0 | fclose(f); |
43 | 0 | return false; |
44 | 0 | } |
45 | 10 | if (fclose(f) != 0) { |
46 | 0 | return false; |
47 | 0 | } |
48 | 10 | return true; |
49 | 10 | } |