Open Model Railroad Network (OpenMRN)
Loading...
Searching...
No Matches
FileUtils.cxx
Go to the documentation of this file.
1
35#include <string>
36
37#include "utils/macros.h"
38
39#ifdef __EMSCRIPTEN__
40
41#include <emscripten.h>
42#include <emscripten/val.h>
43
44string read_file_to_string(const string &filename)
45{
46 using emscripten::val;
47 EM_ASM(var fs = require('fs'); Module.fs = fs;);
48 val fs = val::module_property("fs");
49 string contents = fs.call<val>("readFileSync", string(filename),
50 string("binary")).as<string>();
51 return contents;
52}
53
54void write_string_to_file(const string &filename, const string &data)
55{
56 using emscripten::val;
57 EM_ASM(var fs = require('fs'); Module.fs = fs;);
58 val fs = val::module_property("fs");
59 fs.call<val>("writeFileSync", string(filename),
60 emscripten::typed_memory_view(data.size(), (uint8_t *)data.data()),
61 string("binary"));
62}
63
64#else
65
66#include <stdio.h>
67#include <string.h>
68#include <errno.h>
69
78string read_file_to_string(const string &filename)
79{
80 FILE *f = fopen(filename.c_str(), "rb");
81 if (!f)
82 {
83 fprintf(stderr, "Could not open file %s: %s\n", filename.c_str(),
84 strerror(errno));
85 exit(1);
86 }
87 char buf[1024];
88 size_t nr;
89 string ret;
90 while ((nr = fread(buf, 1, sizeof(buf), f)) > 0)
91 {
92 ret.append(buf, nr);
93 }
94 fclose(f);
95 return ret;
96}
97
104void write_string_to_file(const string &filename, const string &data)
105{
106 FILE *f = fopen(filename.c_str(), "wb");
107 if (!f)
108 {
109 fprintf(stderr, "Could not open file %s: %s\n", filename.c_str(),
110 strerror(errno));
111 exit(1);
112 }
113 size_t nr;
114 size_t offset = 0;
115 string ret;
116 while ((nr = fwrite(data.data() + offset, 1, data.size() - offset, f)) > 0)
117 {
118 offset += nr;
119 if (offset >= data.size())
120 {
121 break;
122 }
123 }
124 if (offset != data.size())
125 {
126 fprintf(stderr, "error writing: %s, offset: %zu, size: %zu\n",
127 strerror(errno), offset, data.size());
128 }
129 fclose(f);
130}
131
132#endif
string read_file_to_string(const string &filename)
Opens a file, reads the entire contents, stores it in a c++ std::string and returns this string.
Definition FileUtils.cxx:78
void write_string_to_file(const string &filename, const string &data)
Opens (or creates) a file, truncates it and overwrites the contents with what is given in a string.