MCPcopy Create free account
hub / github.com/Tracktion/choc / readFileContent

Function readFileContent

choc/text/choc_Files.h:129–170  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

127
128template <typename GetDestBufferFn>
129size_t readFileContent (const std::filesystem::path& filename, GetDestBufferFn&& getBuffer)
130{
131 if (filename.empty())
132 throw Error ("Illegal filename");
133
134 try
135 {
136 std::ifstream stream;
137 stream.exceptions (std::ofstream::failbit | std::ofstream::badbit);
138 stream.open (filename, std::ios::binary | std::ios::ate);
139
140 if (! stream.is_open())
141 {
142 if (! exists (filename))
143 throw Error ("File does not exist: " + filename.string());
144
145 throw Error ("Failed to open file: " + filename.string());
146 }
147
148 auto fileSize = stream.tellg();
149
150 if (fileSize == 0)
151 return 0;
152
153 if (fileSize > 0)
154 {
155 if (auto destBuffer = getBuffer (static_cast<uint64_t> (fileSize)))
156 {
157 stream.seekg (0);
158
159 if (stream.read (static_cast<std::ifstream::char_type*> (destBuffer), static_cast<std::streamsize> (fileSize)))
160 return static_cast<size_t> (fileSize);
161 }
162 }
163
164 throw Error ("Failed to read from file: " + filename.string());
165 }
166 catch (const std::ios_base::failure& e)
167 {
168 throw Error ("Failed to read from file: " + filename.string() + ": " + e.what());
169 }
170}
171
172inline std::string loadFileAsString (const std::filesystem::path& filename)
173{

Callers 1

loadFileAsStringFunction · 0.85

Calls 5

whatMethod · 0.80
ErrorClass · 0.70
emptyMethod · 0.45
openMethod · 0.45
readMethod · 0.45

Tested by

no test coverage detected