Example: Path I/O with ddn.os.path¶
This example demonstrates text and binary file I/O using the Path struct from the ddn.os.path module. It covers creating directories, writing and reading text files with different newline conventions, and performing atomic binary writes.
Source: demo/os/path_io.d¶
/+ dub.sdl:
name "os-path-io"
dependency "ddn" version=">=1.0.0"
+/
// SPDX-License-Identifier: BSD-3-Clause
/**
* Demo: text and binary I/O with ddn.os.path.Path
*
* Run:
* ./demo.sh demo-os-path_io
* or:
* dub run --single demo/os/path_io.d
*/
module demo.os.path_io;
import std.stdio;
import std.file;
import std.path;
import std.uuid : randomUUID;
import std.string : replace;
import ddn.os.path;
void main() {
writeln("=== ddn.os.path I/O demo ===");
auto base = buildPath("tmp_demo_io_" ~ randomUUID().toString());
scope (exit) { if (exists(base)) rmdirRecurse(base); }
Path(base).mkdir(true);
auto textFile = Path(buildPath(base, "hello.txt"));
auto binFile = Path(buildPath(base, "data.bin"));
// Write text with automatic platform newline translation
textFile.writeText("hello\nworld\n");
// Read back with universal newlines (default -> "\n")
auto txt = textFile.readText();
writeln("text contents: ", txt.replace("\n", "\\n"));
// Force CRLF newlines in file
textFile.writeText("A\nB\n", "utf-8", "strict", "\r\n");
auto raw = textFile.readText("utf-8", "strict", ""); // keep as-is
writeln("raw CRLF: ", raw.replace("\r", "\\r").replace("\n", "\\n"));
// Binary I/O round trip and atomic write
import std.array : uninitializedArray, appender;
ubyte[] payload = cast(ubyte[])[0,1,2,3,255,128,0];
binFile.writeBytes(payload, true); // atomic
auto back = binFile.readBytes();
writeln("binary size: ", back.length);
writeln("=== End I/O demo ===");
}
What This Example Shows¶
-
Creating Directories:
UsesPath(base).mkdir(true)to create a temporary directory for the demo. -
Text File I/O:
- Writes text to a file with platform-specific newlines.
- Reads text back and demonstrates newline normalization.
-
Shows how to force CRLF (
\r\n) newlines and read raw file content. -
Binary File I/O:
- Writes a byte array to a file atomically.
-
Reads the binary data back and prints its size.
-
Cleanup:
The temporary directory and files are automatically removed at the end of the program.
Output Example¶
=== ddn.os.path I/O demo ===
text contents: hello\nworld\n
raw CRLF: A\r\nB\r\n
binary size: 7
=== End I/O demo ===
Related Reference¶
- Reference: ddn.os.path
- Demo: Path Basics
- Demo: Path Globbing
- Demo: Path Relativization
- Demo: Path Walking