emilib
file_system.hpp
1 // By Emil Ernerfeldt 2012-2016
2 // LICENSE:
3 // This software is dual-licensed to the public domain and under the following
4 // license: you are granted a perpetual, irrevocable license to copy, modify,
5 // publish, and distribute this file as you see fit.
6 // HISTORY
7 // 2012-11-03 - Created for PipeDreams as FILEWrapper.hpp.
8 // 2014 - Adapted for Ghostel
9 // 2016 - Moved into emilib.
10 
11 #pragma once
12 
13 #include <cstdio>
14 #include <functional>
15 #include <string>
16 #include <vector>
17 
18 namespace fs {
19 
21 {
22 public:
23  FILEWrapper() : _fp(0) {}
24 
26  FILEWrapper(const std::string& path, const char* mode);
27  ~FILEWrapper();
28 
29  void close();
30 
32  bool try_open(const std::string& path, const char* mode);
33 
34  bool error() const;
35  bool end_of_file() const;
36 
37  void read_or_die(void* dest, size_t nbytes);
38 
40  size_t try_read(void* dest, size_t nbytes);
41 
42  void write(const void* src, size_t nbytes);
43 
45  void flush();
46 
48  void seek(int offset, int origin);
49 
50  long tell() const;
51 
53  bool read_line(char* dest, int nbytes);
54 
55  FILE* handle();
56 
57 private:
58  FILE* _fp;
59 
61  FILEWrapper& operator=(FILEWrapper&);
62 };
63 
64 // ------------------------------------------------
65 // Helper for reading/writing/listing files:
66 
67 bool file_exists(const std::string& path);
68 size_t file_size(const std::string& path);
69 time_t modified_time(const std::string& path);
70 bool is_file(const std::string& path);
71 bool is_directory(const std::string& path);
72 std::vector<uint8_t> read_binary_file(const std::string& path);
73 std::string read_text_file(const std::string& path);
74 void write_binary_file(const std::string& path, const void* data, size_t nbytes);
75 void write_text_file(const std::string& path, const char* text);
76 
77 std::vector<std::string> files_in_directory(const std::string& path);
78 
79 void print_tree(const std::string& path, const std::string& indent = "");
80 
82 void walk_dir(const std::string& path, const std::function<void(const std::string&)>& visitor);
83 
84 // ------------------------------------------------
85 // Path handling:
86 
88 std::string file_ending(const std::string& path);
89 
91 std::string without_ending(const std::string& path);
92 
94 std::string strip_path(const std::string& dir_path, const std::string& file_path);
95 
97 std::string file_dir(const std::string& path);
98 
100 std::string file_name(const std::string& path);
101 
103 const char* file_name(const char* path);
104 
105 } // namespace fs
bool read_line(char *dest, int nbytes)
Returns true on success.
bool try_open(const std::string &path, const char *mode)
Nice version.
Definition: file_system.hpp:18
void seek(int offset, int origin)
Origin = SEEK_SET, SEEK_CUR or SEEK_END.
Definition: file_system.hpp:20
size_t try_read(void *dest, size_t nbytes)
Returns the number of read bytes.
void flush()
Write. Now.