comparison dmutil.cpp @ 19:a329f0216491

Implement PLY file format parsing and extremely simplistic scene setup file format. Not finished yet.
author Matti Hamalainen <ccr@tnsp.org>
date Thu, 07 Nov 2019 20:15:33 +0200
parents
children 1404dfcee7b8
comparison
equal deleted inserted replaced
18:b1e75c65016d 19:a329f0216491
1 //
2 //
3 //
4 #include "dmutil.h"
5 #include <fstream>
6
7
8 std::string dmStrLTrim(const std::string& str, const std::string& delim)
9 {
10 return str.substr(str.find_first_not_of(delim));
11 }
12
13
14 std::string dmStrRTrim(const std::string& str, const std::string& delim)
15 {
16 return str.substr(0, str.find_last_not_of(delim));
17 }
18
19
20 std::string dmStrTrim(const std::string& str, const std::string& delim)
21 {
22 if (str.empty())
23 return str;
24
25 size_t start = str.find_first_not_of(delim);
26 return str.substr(start, str.find_last_not_of(delim) - start + 1);
27 }
28
29
30 std::vector<std::string> dmStrSplit(const std::string& str, const std::string& delim)
31 {
32 std::vector<std::string> result;
33 size_t oldpos = 0, newpos;
34
35 do
36 {
37 newpos = str.find_first_of(delim, oldpos);
38 std::string tmp = dmStrTrim(str.substr(oldpos, newpos - oldpos));
39
40 if (!tmp.empty())
41 result.push_back(tmp);
42
43 oldpos = newpos + 1;
44 } while (newpos != std::string::npos);
45
46 return result;
47 }
48
49
50 std::string dmStrJoin(const std::vector<std::string> &list, const std::string &delim)
51 {
52 switch (list.size())
53 {
54 case 0:
55 return "";
56
57 case 1:
58 return list[0];
59
60 default:
61 std::string result;
62 bool first = true;
63 for (const auto &elem : list)
64 {
65 if (!first)
66 result += delim;
67 else
68 first = false;
69 result += elem;
70 }
71 return result;
72 }
73 }
74
75
76 bool dmReadText(const std::string &filename, std::string &buf, const int maxSize)
77 {
78 std::ifstream in(filename.c_str(), std::fstream::in);
79
80 if (!in.is_open())
81 {
82 printf("ERROR: Unable to open file '%s'.\n",
83 filename.c_str());
84 return false;
85 }
86
87 in.seekg(0, std::ios::end);
88
89 if (in.tellg() > maxSize)
90 {
91 printf("ERROR: File '%s' is too large.\n",
92 filename.c_str());
93 return false;
94 }
95
96 buf.reserve(in.tellg());
97 in.seekg(0, std::ios::beg);
98
99 buf.assign((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
100
101 return true;
102 }
103
104
105 bool dmFileExists(const std::string &filename, std::ios_base::openmode mode)
106 {
107 std::ifstream infile(filename.c_str(), mode);
108 return infile.good();
109 }