Example: Path Basics (demo.os.path)¶
This example demonstrates the core features of the ddn.os.path module, showcasing how to create, manipulate, and interact with filesystem paths in D using the high-level Path struct.
Source: demo/os/path.d¶
module demo.os.path;
import std.stdio;
import std.file;
import std.path;
import ddn.os.path;
void main() {
writeln("=== ddn.os.path Demo ===");
// 1. Create Path objects
auto p1 = Path("foo/bar/baz.txt");
auto p2 = Path("/tmp/example.txt");
p2.touch;
writeln("Path 1: ", p1.str());
writeln("Path 2: ", p2.str());
// 2. Join paths
auto joined = Path("foo") / "bar" / "baz.txt";
writeln("Joined path: ", joined.str());
// 3. Get absolute path
writeln("Absolute of p1: ", p1.absolute().str());
// 4. Parent and parents
writeln("Parent of p1: ", p1.parent().str());
writeln("All parents of p1:");
foreach (par; p1.parents())
writeln(" ", par.str());
// 5. File name and stem
writeln("File name of p1: ", p1.name());
writeln("Stem of p1: ", p1.stem());
writeln("Extension of p1: ", p1.suffix());
// 6. Check existence and type
writeln("Does p2 exist? ", p2.exists());
writeln("Is p2 a file? ", p2.isFile());
writeln("Is p2 a directory? ", p2.isDir());
// 7. Demonstrate directory creation and removal
auto demoDir = Path("demo_dir");
if (!demoDir.exists()) {
demoDir.mkdir();
writeln("Created directory: ", demoDir.str());
}
if (demoDir.exists()) {
demoDir.remove();
writeln("Removed directory: ", demoDir.str());
}
// 8. Symlink and hardlink (if supported)
version (Posix) {
auto target = Path("target_file.txt");
std.file.write(target.str(), "Hello, world!");
auto symlinkPath = Path("symlink_to_target.txt");
auto hardlinkPath = Path("hardlink_to_target.txt");
if (!symlinkPath.exists()) {
symlinkPath.symlinkTo(target.str());
writeln("Created symlink: ", symlinkPath.str());
}
if (!hardlinkPath.exists()) {
hardlinkPath.hardlinkTo(target.str());
writeln("Created hardlink: ", hardlinkPath.str());
}
// Clean up
symlinkPath.exists() && std.file.remove(symlinkPath.str());
hardlinkPath.exists() && std.file.remove(hardlinkPath.str());
target.exists() && std.file.remove(target.str());
}
// 9. Path comparison
auto p3 = Path("foo/bar/../bar/baz.txt").absolute();
writeln("p1 == p3? ", p1.absolute() == p3);
writeln("=== End of Demo ===");
}
What This Example Shows¶
- Path Creation: Instantiating
Pathobjects from strings. - Joining Paths: Using
/operator for intuitive path joining. - Path Properties: Getting absolute paths, parent directories, file names, stems, and extensions.
- Filesystem Checks: Testing for existence, file/dir type, and performing file/directory operations.
- Symlinks/Hardlinks: Creating and cleaning up links (on POSIX systems).
- Path Comparison: Comparing normalized/absolute paths for equality.
How to Run¶
You can run this example using DUB or directly with the D compiler:
dub run --single demo/os/path.d
Or, if you have a build script:
./demo.sh demo-os-path