File Example
Common File Operations Including Creation, Deletion, Reading, Writing, and Closing
Code:
import std.fs.*
import std.io.*
main() {
let filePath: Path = Path("./tempFile.txt")
if (exists(filePath)) {
remove(filePath)
}
/* Create a file 'tempFile.txt' in the current directory in write-only mode, write "123456789\n" to the file three times, and close the file. */
var file: File = File(filePath, Write)
if (exists(filePath)) {
println("The file 'tempFile.txt' is created successfully in current directory.\n")
}
let bytes: Array<Byte> = "123456789\n".toArray()
for (_ in 0..3) {
file.write(bytes)
}
file.close()
/* Open the './tempFile.txt' file in append mode, write "abcdefghi\n" to the file, and close the file. */
file = File(filePath, Append)
file.write("abcdefghi\n".toArray())
file.close()
/* Open the './tempFile.txt' file in read-only mode, read data in the file as required, and close the file. */
file = File(filePath, Read)
let bytesBuf: Array<Byte> = Array<Byte>(10, repeat: 0)
// Read a piece of data of 10 bytes after the 10th byte in the file header.
file.seek(SeekPosition.Begin(10))
file.read(bytesBuf)
println("Data of the 10th byte after the 10th byte: ${String.fromUtf8(bytesBuf)}")
// Read a piece of data of 10 bytes in the file trailer.
file.seek(SeekPosition.End(-10))
file.read(bytesBuf)
println("Data of the last 10 bytes: ${String.fromUtf8(bytesBuf)}")
file.close()
/* Open the './tempFile.txt' file in read/write mode, perform operations as required, and close the file. */
file = File(filePath, ReadWrite)
// Truncate the file to 0 bytes.
file.setLength(0)
// Write new data to the file.
file.write("The file was truncated to an empty file!".toArray())
// Reset the cursor to the file header.
file.seek(SeekPosition.Begin(0))
// Read file content.
let allBytes: Array<Byte> = readToEnd(file)
// Close the file.
file.close()
println("Data written newly: ${String.fromUtf8(allBytes)}")
remove(filePath)
return 0
}
Results:
The file 'tempFile.txt' is created successfully in current directory.
Data of the 10th byte after the 10th byte: 123456789
Data of the last 10 bytes: abcdefghi
Data written newly: The file was truncated to an empty file!
Demonstration of static Functions of File
Code:
import std.fs.*
main() {
let filePath: Path = Path("./tempFile.txt")
if (exists(filePath)) {
remove(filePath)
}
/* Create a file in write-only mode, write "123456789\n" to the file, and close the file. */
var file: File = File.create(filePath)
file.write("123456789\n".toArray())
file.close()
/* Write "abcdefghi\n" to the file in append mode. */
File.appendTo(filePath, "abcdefghi".toArray())
/* Directly read all data in the file. */
let allBytes: Array<Byte> = File.readFrom(filePath)
println(String.fromUtf8(allBytes))
remove(filePath)
return 0
}
Results:
123456789
abcdefghi