Directory Example
Demonstration of Basic Operations of Directory
Code:
import std.fs.*
main() {
let testDirPath: Path = Path("./testDir")
let subDirPath: Path = Path("./testDir/subDir")
if (Directory.exists(testDirPath)) {
Directory.delete(testDirPath, recursive: true)
}
/* Recursively creates a directory and "./testDir/subDir". */
let subDir: Directory = Directory.create(subDirPath, recursive: true)
if (Directory.exists(subDirPath)) {
println("The directory './testDir/subDir' is successfully created recursively in current directory.")
}
/* Creates the subdirectory "dir1" in "./testDir/subDir". */
subDir.createSubDirectory("dir1")
if (Directory.exists("./testDir/subDir/dir1")) {
println("The directory 'dir1' is created successfully in directory './testDir/subDir'.")
}
/* Creates the subfile "file1" in "./testDir/subDir". */
subDir.createFile("file1")
if (File.exists("./testDir/subDir/file1")) {
println("The file 'file1' is created successfully in directory './testDir/subDir'.")
}
/* Creates a temporary directory in "./testDir". */
let tempDir: Directory = Directory.createTemp(testDirPath)
let tempDirPath: Path = tempDir.info.path
if (Directory.exists(tempDirPath)) {
println("The temporary directory is created successfully in directory './testDir'.")
}
/* Moves "subDir" to the temporary directory and renames it "subDir_new". */
let newSubDirPath: Path = tempDirPath.join("subDir_new")
Directory.move(subDirPath, newSubDirPath, false)
if (Directory.exists(newSubDirPath) && !Directory.exists(subDirPath)) {
println("The directory './testDir/subDir' is moved successfully to the temporary directory and renamed 'subDir_new'.")
}
/* Copies "subDir_new" to "./testDir" and renames it "subDir". */
Directory.copy(newSubDirPath, subDirPath, false)
if (Directory.exists(subDirPath) && Directory.exists(newSubDirPath)) {
println("The directory 'subDir_new' is copied successfully to directory './testDir' and renamed 'subDir'.")
}
Directory.delete(testDirPath, recursive: true)
return 0
}
Running result:
The directory './testDir/subDir' is successfully created recursively in current directory.
The directory 'dir1' is created successfully in directory './testDir/subDir'.
The file 'file1' is created successfully in directory './testDir/subDir'.
The temporary directory is created successfully in directory './testDir'.
The directory './testDir/subDir' is moved successfully to the temporary directory and renamed 'subDir_new'.
The directory 'subDir_new' is copied successfully to directory './testDir' and renamed 'subDir'.