diff options
author | George Hazan <george.hazan@gmail.com> | 2024-01-17 18:05:48 +0300 |
---|---|---|
committer | George Hazan <george.hazan@gmail.com> | 2024-01-17 18:05:48 +0300 |
commit | 78034bcd615e739ad51a1b4bc570b6f1927932fc (patch) | |
tree | 3584b0810f26158351a509d815ab61bdc00f8f52 /libs/libjson/src/libJSON.cpp | |
parent | 88da7ba66825d1e04f64ef36db9cbac1d7fec582 (diff) |
json2file + file2json = helpers to load json from file and write it back
Diffstat (limited to 'libs/libjson/src/libJSON.cpp')
-rw-r--r-- | libs/libjson/src/libJSON.cpp | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/libs/libjson/src/libJSON.cpp b/libs/libjson/src/libJSON.cpp index 7cd2255d4a..3dd7544afa 100644 --- a/libs/libjson/src/libJSON.cpp +++ b/libs/libjson/src/libJSON.cpp @@ -458,3 +458,43 @@ LIBJSON_DLL(int) json_equal(JSONNode *node, JSONNode *node2) { JSON_ASSERT_SAFE(node2, JSON_TEXT("null node2 to json_equal"), return false;);
return *node == *node2;
}
+
+/////////////////////////////////////////////////////////////////////////////////////////
+
+LIBJSON_DLL(bool) file2json(const wchar_t *pwszFilename, JSONNode &root)
+{
+ if (!pwszFilename)
+ return false;
+
+ int fileId = _wopen(pwszFilename, _O_BINARY | _O_RDONLY);
+ if (fileId == -1)
+ return false;
+
+ size_t dwFileLength = _filelength(fileId), dwReadLen;
+ ptrA szBuf((char *)mir_alloc(dwFileLength + 1));
+ dwReadLen = _read(fileId, szBuf, (unsigned)dwFileLength);
+ _close(fileId);
+ if (dwFileLength != dwReadLen)
+ return false;
+
+ szBuf[dwFileLength] = 0;
+
+ root = JSONNode::parse(szBuf);
+ if (!root)
+ return false;
+
+ return true;
+}
+
+LIBJSON_DLL(bool) json2file(const JSONNode &root, const wchar_t *pwszFilename)
+{
+ auto szBody = root.write_formatted();
+
+ int fileId = _wopen(pwszFilename, _O_CREAT | _O_TRUNC | _O_WRONLY, _S_IREAD | _S_IWRITE);
+ if (fileId == -1)
+ return false;
+
+ int cbLen = _write(fileId, szBody.c_str(), (unsigned)szBody.length());
+ _close(fileId);
+ return cbLen == (int)szBody.length();
+}
|