gramods
StringFile.hh
1 
6 #ifndef GRAMODS_CORE_STRINGFILE
7 #define GRAMODS_CORE_STRINGFILE
8 
9 #include <gmCore/config.hh>
10 #include <gmCore/PreConditionViolation.hh>
11 
12 #include <optional>
13 
14 #include <stdio.h>
15 #include <string.h>
16 
17 BEGIN_NAMESPACE_GMCORE
18 
24 struct StringFile {
25 
30  if (file_ptr) fclose(*file_ptr);
31  }
32 
37  FILE * getFilePtr() {
38  if (!file_ptr) file_ptr = tmpfile();
39  return *file_ptr;
40  }
41 
47  std::string finalize() {
48  if (!file_ptr) throw PreConditionViolation("Cannot finalize - not open");
49 
50  rewind(*file_ptr);
51 
52  char buffer [256];
53  std::stringstream ss;
54 
55  while (!feof(*file_ptr)) {
56  if (fgets(buffer, 256, *file_ptr) == NULL) break;
57  ss << buffer;
58  }
59 
60  fclose(*file_ptr);
61  file_ptr = std::nullopt;
62 
63  return ss.str();
64  }
65 
66 private:
67  std::optional<FILE*> file_ptr;
68 };
69 
70 END_NAMESPACE_GMCORE
71 
72 #endif
Standard exception for violation of pre conditions in a call to a function or object.
Definition: PreConditionViolation.hh:16
This struct creates a FILE pointer to a temporary file and reads off this file's data into string whe...
Definition: StringFile.hh:24
~StringFile()
Closes the temporary file if this has not already been done.
Definition: StringFile.hh:29
FILE * getFilePtr()
Returns the FILE pointer to a temporary file after, if not already done, creating such a FILE object.
Definition: StringFile.hh:37
std::string finalize()
Rewinds and reads off the temporary file into a string, closes the FILE object and returns the string...
Definition: StringFile.hh:47