Last active
May 11, 2018 16:20
-
-
Save truedat101/9e7eeb0c22c7e8fc8dde5f205e1aa0cc to your computer and use it in GitHub Desktop.
A simple example of writing a formatted string out to a file or to json in Dlang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import std.stdio; | |
import std.string; | |
import std.file; | |
import std.json; | |
static const auto HK_DB = "hk_db.json"; // this is the filename | |
// | |
// Use a formatting string to fill in values for this config file | |
// | |
static const auto HAP_SERVICE_DEF_FORMAT = "%s\n" ~ | |
"_hap._tcp.\n" ~ | |
"8008\n" ~ // XXX PORTNO should be configured | |
"c#=%s\n" ~ | |
"ff=%s\n" ~ | |
"id=%s\n" ~ | |
"md=%s\n" ~ | |
"pv=1.0\n" ~ | |
"s#=%s\n" ~ | |
"sf=%s\n" ~ | |
"ci=%s\n" ~ | |
"Priority=0\n" ~ | |
"Weight=0\n" ~ | |
"Port=8008\n" ~ | |
"Target=%s\n"; | |
// | |
// Ignoring that we don't have all of these variables defined, focus on the idea | |
// We fill the format string with values and write to a file | |
std.file.write(HAP_SERVICE_DEF_TXT, format(HAP_SERVICE_DEF_FORMAT, mdns_name, params["HK_CNUM"], params["HK_FF"], chomp(params["HK_ID"]), params["HK_MD"], params["HK_SNUM"], params["HK_SF"], params["HK_CI"], mdns_hostname)); // XXX Add exception handling | |
// Here's another example with json | |
static void write_hk_db(JSONValue jsondata) { // XXX If this is all we do, we don't need a special function | |
immutable jsonstr = jsondata.toString(); | |
std.file.write(HK_DB, jsonstr); | |
} | |
static JSONValue load_hk_db() { | |
auto datastr = `{ "cnum" : 1, "snum": 1}`; | |
if (!exists(HK_DB.dup)) { | |
std.file.write(HK_DB, datastr); // XXX Add exception handling | |
writeln("HK_DB file does not exist, created, and wrote ", datastr); | |
} else { | |
datastr = std.file.readText(HK_DB); | |
writeln("HK_DB read ", datastr); | |
} | |
JSONValue jsondata = parseJSON(datastr); | |
return jsondata; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note, the above won't compile, however, you can borrow the ideas, which are just really basic example of writing data out to a file. A little more robustness is needed. Also, writes are synchronous.