-
Notifications
You must be signed in to change notification settings - Fork 33
/
file-ops.h
53 lines (40 loc) · 1.17 KB
/
file-ops.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#pragma once
#include <fstream>
#include <iostream>
// stream string operations derived from:
// Optimized C++ by Kurt Guntheroth (O’Reilly).
// Copyright 2016 Kurt Guntheroth, 978-1-491-92206-4
namespace fileops
{
inline std::streamoff stream_size(std::istream& file)
{
std::istream::pos_type current_pos = file.tellg();
if (current_pos == std::istream::pos_type(-1)) {
return -1;
}
file.seekg(0, std::istream::end);
std::istream::pos_type end_pos = file.tellg();
file.seekg(current_pos);
return end_pos - current_pos;
}
inline bool stream_read_string(std::istream& file, std::string& fileContents)
{
std::streamoff len = stream_size(file);
if (len == -1) {
return false;
}
fileContents.resize(static_cast<std::string::size_type>(len));
file.read(&fileContents[0], fileContents.length());
return true;
}
inline bool read_file(const std::string& filename, std::string& fileContents)
{
std::ifstream file(filename, std::ios::binary);
if (!file.is_open()) {
return false;
}
const bool success = stream_read_string(file, fileContents);
file.close();
return success;
}
} // namespace fileops