commit 94a27bfc769e307458b40c6c2b6c31483eced237
parent a8cfbfd6b21a26ee790d6fd828f55ce0ce8ab924
Author: Oshgnacknak <osh@oshgnacknak.de>
Date: Mon, 7 Mar 2022 14:17:31 +0100
Add fileContentAsBuffer procedure and example
Diffstat:
2 files changed, 37 insertions(+), 0 deletions(-)
diff --git a/examples/file_content_as_buffer.cpp b/examples/file_content_as_buffer.cpp
@@ -0,0 +1,20 @@
+#include "osh.h"
+
+using namespace osh;
+
+int main() {
+ StringBuffer sb = fileContentAsBuffer(__FILE__);
+ auto destruct_sb = autoDestruct(sb);
+
+ printp(sb, "\n");
+ printp(sb, "void foo() {\n");
+ printp(sb, " println(\"Hallo Welt\");\n");
+ printp(sb, "}\n");
+
+ println(sb);
+
+ return 0;
+}
+
+#define OSH_H_IMPLEMENTATION
+#include "osh.h"
diff --git a/osh.h b/osh.h
@@ -112,6 +112,8 @@ namespace osh {
void print1(Formatter auto&, const StringBuffer&);
+ StringBuffer fileContentAsBuffer(const char* filename);
+
int listIndex(int index, const int& size);
template<typename T>
@@ -370,6 +372,21 @@ namespace osh {
printp(fmt, s.cstr());
}
+ StringBuffer fileContentAsBuffer(const char* filename) {
+ FILE* f = fopen(filename, "r");
+ assert(f != NULL);
+
+ fseek(f, 0, SEEK_END);
+ int capacity = ftell(f);
+ StringBuffer s(capacity);
+
+ rewind(f);
+ int read = fread(s.cstr(), sizeof(char), capacity, f);
+ assert(read == capacity);
+
+ s.setSize(capacity);
+ return s;
+ }
int listIndex(int index, const int& size) {
assert(index >= -size && index < size,