LIPH's C++ Codes
file.h
Go to the documentation of this file.
1#ifndef LIPH_FILE_H_
2#define LIPH_FILE_H_
3
4#include <cstdio>
5#include <filesystem>
6#include <memory>
7#include <string>
8#include <vector>
9
10namespace liph {
11
13[[nodiscard]] bool read_file(const std::filesystem::path& pathname, std::string& output);
14
16[[nodiscard]] bool write_file(const std::filesystem::path& pathname, const std::string& str);
17
19[[nodiscard]] bool path_exists(const std::string& pathname);
20
22[[nodiscard]] std::vector<std::string> list_files(const std::string& pathname);
23
24using file_ptr = std::unique_ptr<FILE, decltype([](FILE *f) {
25 if (f) fclose(f);
26})>;
27
28inline file_ptr fopen(const char *filename, char const *mode) {
29 FILE *f = ::fopen(filename, mode);
30 return file_ptr(f);
31}
32
35inline bool mkdir(const std::filesystem::path& path) {
36 std::error_code ec;
37 return std::filesystem::create_directory(path, ec);
38}
39
42inline bool mkdirp(const std::filesystem::path& path) {
43 std::error_code ec;
44 return std::filesystem::create_directories(path, ec);
45}
46
47} // namespace liph
48
49#endif // LIPH_FILE_H_
Definition: algorithm.h:10
bool read_file(const std::filesystem::path &pathname, std::string &output)
read all from pathname, append to output
Definition: file.cpp:9
bool write_file(const std::filesystem::path &pathname, const std::string &str)
write all to pathname
Definition: file.cpp:27
std::vector< std::string > list_files(const std::string &pathname)
list all files(including directories) in pathname recursively and sort by names
Definition: file.cpp:41
bool mkdirp(const std::filesystem::path &path)
Definition: file.h:42
bool mkdir(const std::filesystem::path &path)
Definition: file.h:35
bool path_exists(const std::string &pathname)
check path(file or directory) exists
Definition: file.cpp:36
file_ptr fopen(const char *filename, char const *mode)
Definition: file.h:28
std::unique_ptr< FILE, decltype([](FILE *f) { if(f) fclose(f) file_ptr
Definition: file.h:25