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