From 78034bcd615e739ad51a1b4bc570b6f1927932fc Mon Sep 17 00:00:00 2001 From: George Hazan Date: Wed, 17 Jan 2024 18:05:48 +0300 Subject: json2file + file2json = helpers to load json from file and write it back --- libs/libjson/src/libJSON.cpp | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) (limited to 'libs/libjson/src/libJSON.cpp') 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(); +} -- cgit v1.2.3