Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A simple example of writing a formatted string out to a file or to json in Dlang
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" ~
// 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;

This comment has been minimized.

Copy link
Owner Author

@truedat101 truedat101 commented May 11, 2018

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.