# Filesystem Library (filesystem)
# Difficulty: 2
# Description: Examples of using the Filesystem Library in Razen
## Introduction
The Filesystem Library (`filesystem`) provides functions for working with files and directories in Razen. This library helps you read and write files, create and manage directories, and perform various file system operations.
## Library Overview
### Filesystem Library Functions
- `exists` → Checks if a path exists
- `is_file` → Checks if a path is a file
- `is_dir` → Checks if a path is a directory
- `create_dir` → Creates a directory
- `read_file` → Reads the contents of a file
- `write_file` → Writes content to a file
- `append_file` → Appends content to a file
- `copy` → Copies a file
- `move` → Moves a file or directory
- `remove` → Removes a file or directory
- `list_dir` → Lists the contents of a directory
- `file_size` → Gets the size of a file
- `last_modified` → Gets the last modified time of a file
- `extension` → Gets the extension of a file
- `file_stem` → Gets the name of a file without extension
- `parent_dir` → Gets the parent directory of a path
- `join_path` → Joins path segments
- `absolute_path` → Gets the absolute path
- `current_dir` → Gets the current working directory
- `temp_file` → Creates a temporary file
- `temp_dir` → Creates a temporary directory
## How to Use the Filesystem Library
### Library Import
To use the Filesystem Library in Razen, you first need to import it using the `lib` keyword:
```razen
lib filesystem;
```
### Function Calling
Once imported, you can call functions from the library using the double colon `::` syntax:
```razen
filesystem::functionName(parameters);
```
**Note about bracket notation (Legacy):**
In older versions of Razen (before beta v0.1.75), you could also use bracket notation for library functions:
```razen
# DEPRECATED - Only works in Razen before beta v0.1.75
filesystem[functionName](parameters);
```
This syntax is no longer supported in newer versions of Razen.
## Basic Examples
### Checking Path Existence
```razen
# Import the filesystem library
lib filesystem;
# Check if a file exists
bool fileExists = filesystem::exists("./data.txt");
show "File exists: " + fileExists;
# Check if a directory exists
bool dirExists = filesystem::exists("./documents");
show "Directory exists: " + dirExists;
```
### Creating Directories
```razen
# Import the filesystem library
lib filesystem;
# Create a directory
bool created = filesystem::create_dir("./my_documents");
show "Directory created: " + created;
# Create nested directories
bool nestedCreated = filesystem::create_dir("./my_documents/nested/folder");
show "Nested directories created: " + nestedCreated;
```
### Reading and Writing Files
```razen
# Import the filesystem library
lib filesystem;
# Write content to a file
# The third parameter (false) means don't append, overwrite if exists
bool written = filesystem::write_file("./hello.txt", "Hello, Razen Filesystem!", false);
show "File written: " + written;
# Read content from a file
str content = filesystem::read_file("./hello.txt");
show "File content: " + content;
# Append content to a file
bool appended = filesystem::append_file("./hello.txt", "\nThis is a new line.");
show "Content appended: " + appended;
# Read the updated content
str updatedContent = filesystem::read_file("./hello.txt");
show "Updated content: " + updatedContent;
```
### Checking File Types
```razen
# Import the filesystem library
lib filesystem;
# Check if path is a file
bool isFile = filesystem::is_file("./hello.txt");
show "Is file: " + isFile;
# Check if path is a directory
bool isDir = filesystem::is_dir("./my_documents");
show "Is directory: " + isDir;
```
### Copying and Moving Files
```razen
# Import the filesystem library
lib filesystem;
# Copy a file
bool copied = filesystem::copy("./hello.txt", "./my_documents/hello_copy.txt");
show "File copied: " + copied;
# Move a file
bool moved = filesystem::move("./hello.txt", "./my_documents/hello_moved.txt");
show "File moved: " + moved;
```
### Listing Directory Contents
```razen
# Import the filesystem library
lib filesystem;
# List directory contents
str contents = filesystem::list_dir("./my_documents");
show "Directory contents: " + contents;
# Check if specific files exist in the directory
for (num i = 0; i < contents.length; i = i + 1) {
show "Found: " + contents[i];
}
```
### Getting File Information
```razen
# Import the filesystem library
lib filesystem;
# Get file size
num size = filesystem::file_size("./my_documents/hello_copy.txt");
show "File size: " + size + " bytes";
# Get last modified time
num lastModified = filesystem::last_modified("./my_documents/hello_copy.txt");
show "Last modified timestamp: " + lastModified;
# Get file extension
str ext = filesystem::extension("./my_documents/hello_copy.txt");
show "File extension: " + ext;
# Get file stem (name without extension)
str stem = filesystem::file_stem("./my_documents/hello_copy.txt");
show "File stem: " + stem;
```
### Working with Paths
```razen
# Import the filesystem library
lib filesystem;
# Get parent directory
str parent = filesystem::parent_dir("./my_documents/nested/folder");
show "Parent directory: " + parent;
# Join path segments
str joined = filesystem::join_path(["my_documents", "nested", "file.txt"]);
show "Joined path: " + joined;
# Get absolute path
str absolute = filesystem::absolute_path("./my_documents");
show "Absolute path: " + absolute;
# Get current directory
str current = filesystem::current_dir();
show "Current directory: " + current;
```
### Creating Temporary Files and Directories
```razen
# Import the filesystem library
lib filesystem;
# Create a temporary file
str tempFile = filesystem::temp_file();
show "Temporary file created: " + tempFile;
# Write to the temporary file
filesystem::write_file(tempFile, "This is temporary content", false);
# Create a temporary directory
str tempDir = filesystem::temp_dir();
show "Temporary directory created: " + tempDir;
```
### Removing Files and Directories
```razen
# Import the filesystem library
lib filesystem;
# Remove a file
bool fileRemoved = filesystem::remove("./my_documents/hello_copy.txt");
show "File removed: " + fileRemoved;
# Remove a directory (and its contents)
bool dirRemoved = filesystem::remove("./my_documents/nested");
show "Directory removed: " + dirRemoved;
```
## Advanced Examples
### File Copy Utility
```razen
# Import the filesystem library
lib filesystem;
# Function to copy all files from one directory to another
fun copyDirectory(str sourceDir, str targetDir) {
# Check if source directory exists
if (!filesystem::exists(sourceDir) || !filesystem::is_dir(sourceDir)) {
return "Error: Source directory does not exist or is not a directory";
}
# Create target directory if it doesn't exist
if (!filesystem::exists(targetDir)) {
filesystem::create_dir(targetDir);
} else if (!filesystem::is_dir(targetDir)) {
return "Error: Target path exists but is not a directory";
}
# Get list of files in source directory
str files = filesystem::list_dir(sourceDir);
# Track statistics
num copied = 0;
num failed = 0;
# Copy each file
for (num i = 0; i < files.length; i = i + 1) {
str sourcePath = filesystem::join_path([sourceDir, files[i]]);
str targetPath = filesystem::join_path([targetDir, files[i]]);
# Only copy files, not directories
if (filesystem::is_file(sourcePath)) {
bool success = filesystem::copy(sourcePath, targetPath);
if (success) {
copied = copied + 1;
} else {
failed = failed + 1;
}
}
}
return "Copy complete. " + copied + " files copied, " + failed + " failed.";
}
# Test the copy directory function
show copyDirectory("./source_folder", "./backup_folder");
```
### File Search Utility
```razen
# Import the filesystem library
lib filesystem;
# Function to search for files with a specific extension
fun findFilesByExtension(str directory, str extension) {
# Check if directory exists
if (!filesystem::exists(directory) || !filesystem::is_dir(directory)) {
return "Error: Directory does not exist or is not a directory";
}
# Get list of files in directory
str files = filesystem::list_dir(directory);
# Filter files by extension
str matchingFiles = [];
for (num i = 0; i < files.length; i = i + 1) {
str filePath = filesystem::join_path([directory, files[i]]);
# Check if it's a file and has the right extension
if (filesystem::is_file(filePath) && filesystem::extension(filePath) == extension) {
matchingFiles.push(files[i]);
}
}
return matchingFiles;
}
# Test the file search function
str textFiles = findFilesByExtension("./documents", "txt");
show "Text files found: " + textFiles;
```
### File Backup Utility
```razen
# Import the filesystem library
lib filesystem;
# Function to create a backup of a file with timestamp
fun backupFile(str filePath) {
# Check if file exists
if (!filesystem::exists(filePath) || !filesystem::is_file(filePath)) {
return "Error: File does not exist or is not a file";
}
# Get current timestamp
num timestamp = Date.now();
# Get file components
str directory = filesystem::parent_dir(filePath);
str filename = filesystem::file_stem(filePath);
str extension = filesystem::extension(filePath);
# Create backup filename with timestamp
str backupFilename = filename + "_backup_" + timestamp + "." + extension;
str backupPath = filesystem::join_path([directory, backupFilename]);
# Copy the file to create backup
bool success = filesystem::copy(filePath, backupPath);
if (success) {
return "Backup created: " + backupPath;
} else {
return "Error: Failed to create backup";
}
}
# Test the backup function
show backupFile("./important_document.txt");
```
## Practical Application: Simple File Manager
```razen
# Import the filesystem library
lib filesystem;
# Simple file manager class
class FileManager {
# Constructor
init(str rootDirectory) {
this.rootDirectory = rootDirectory;
this.currentDirectory = rootDirectory;
# Create root directory if it doesn't exist
if (!filesystem::exists(rootDirectory)) {
filesystem::create_dir(rootDirectory);
}
}
# List files and directories in current directory
fun listContents() {
if (!filesystem::exists(this.currentDirectory)) {
return "Error: Current directory does not exist";
}
str contents = filesystem::list_dir(this.currentDirectory);
if (contents.length == 0) {
return "Directory is empty";
}
str result = "Contents of " + this.currentDirectory + ":\n";
for (num i = 0; i < contents.length; i = i + 1) {
str itemPath = filesystem::join_path([this.currentDirectory, contents[i]]);
if (filesystem::is_dir(itemPath)) {
result = result + "[DIR] " + contents[i] + "\n";
} else {
num size = filesystem::file_size(itemPath);
result = result + "[FILE] " + contents[i] + " (" + size + " bytes)\n";
}
}
return result;
}
# Change current directory
fun changeDirectory(str directory) {
# Handle special case for parent directory
if (directory == "..") {
# Don't go above root directory
if (this.currentDirectory == this.rootDirectory) {
return "Already at root directory";
}
this.currentDirectory = filesystem::parent_dir(this.currentDirectory);
return "Changed to " + this.currentDirectory;
}
# Handle absolute paths
str targetDir;
if (directory.startsWith("/") || directory.startsWith("./") || directory.startsWith("../")) {
targetDir = directory;
} else {
# Relative path
targetDir = filesystem::join_path([this.currentDirectory, directory]);
}
# Check if target directory exists
if (!filesystem::exists(targetDir) || !filesystem::is_dir(targetDir)) {
return "Error: Directory does not exist or is not a directory";
}
this.currentDirectory = targetDir;
return "Changed to " + this.currentDirectory;
}
# Create a new directory
fun createDirectory(str directoryName) {
str newDirPath = filesystem::join_path([this.currentDirectory, directoryName]);
if (filesystem::exists(newDirPath)) {
return "Error: Path already exists";
}
bool created = filesystem::create_dir(newDirPath);
if (created) {
return "Directory created: " + directoryName;
} else {
return "Error: Failed to create directory";
}
}
# Create a new file with content
fun createFile(str filename, str content) {
str filePath = filesystem::join_path([this.currentDirectory, filename]);
if (filesystem::exists(filePath)) {
return "Error: File already exists";
}
bool created = filesystem::write_file(filePath, content, false);
if (created) {
return "File created: " + filename;
} else {
return "Error: Failed to create file";
}
}
# Read a file
fun readFile(str filename) {
str filePath = filesystem::join_path([this.currentDirectory, filename]);
if (!filesystem::exists(filePath) || !filesystem::is_file(filePath)) {
return "Error: File does not exist or is not a file";
}
str content = filesystem::read_file(filePath);
return "Contents of " + filename + ":\n" + content;
}
# Delete a file or directory
fun delete(str name) {
str path = filesystem::join_path([this.currentDirectory, name]);
if (!filesystem::exists(path)) {
return "Error: Path does not exist";
}
bool removed = filesystem::remove(path);
if (removed) {
if (filesystem::is_dir(path)) {
return "Directory deleted: " + name;
} else {
return "File deleted: " + name;
}
} else {
return "Error: Failed to delete";
}
}
# Get current working directory
fun getCurrentDirectory() {
return "Current directory: " + this.currentDirectory;
}
}
# Create a file manager instance
FileManager manager = new FileManager("./file_manager_root");
# Demonstrate file manager operations
show manager.getCurrentDirectory();
show manager.createDirectory("documents");
show manager.createDirectory("images");
show manager.listContents();
show manager.changeDirectory("documents");
show manager.getCurrentDirectory();
show manager.createFile("notes.txt", "This is a test file.\nIt contains multiple lines.\nCreated by Razen File Manager.");
show manager.listContents();
show manager.readFile("notes.txt");
show manager.changeDirectory("..");
show manager.getCurrentDirectory();
show manager.listContents();
```
## Summary
The Filesystem Library in Razen provides essential functions for working with files and directories:
- File operations: `read_file`, `write_file`, `append_file`, `copy`, `move`, `remove`
- Directory operations: `create_dir`, `list_dir`, `remove`
- Path operations: `join_path`, `parent_dir`, `absolute_path`, `current_dir`
- Information functions: `exists`, `is_file`, `is_dir`, `file_size`, `last_modified`, `extension`, `file_stem`
- Temporary file/directory creation: `temp_file`, `temp_dir`
These functions help you work with the file system efficiently in your Razen programs.
# Filesystem Library (filesystem)
# Difficulty: 2
# Description: Examples of using the Filesystem Library in Razen
## Introduction
The Filesystem Library (`filesystem`) provides functions for working with files and directories in Razen. This library helps you read and write files, create and manage directories, and perform various file system operations.
## Library Overview
### Filesystem Library Functions
- `exists` → Checks if a path exists
- `is_file` → Checks if a path is a file
- `is_dir` → Checks if a path is a directory
- `create_dir` → Creates a directory
- `read_file` → Reads the contents of a file
- `write_file` → Writes content to a file
- `append_file` → Appends content to a file
- `copy` → Copies a file
- `move` → Moves a file or directory
- `remove` → Removes a file or directory
- `list_dir` → Lists the contents of a directory
- `file_size` → Gets the size of a file
- `last_modified` → Gets the last modified time of a file
- `extension` → Gets the extension of a file
- `file_stem` → Gets the name of a file without extension
- `parent_dir` → Gets the parent directory of a path
- `join_path` → Joins path segments
- `absolute_path` → Gets the absolute path
- `current_dir` → Gets the current working directory
- `temp_file` → Creates a temporary file
- `temp_dir` → Creates a temporary directory
## How to Use the Filesystem Library
### Library Import
To use the Filesystem Library in Razen, you first need to import it using the `lib` keyword:
```razen
lib filesystem;
```
### Function Calling
Once imported, you can call functions from the library using the double colon `::` syntax:
```razen
filesystem::functionName(parameters);
```
**Note about bracket notation (Legacy):**
In older versions of Razen (before beta v0.1.75), you could also use bracket notation for library functions:
```razen
# DEPRECATED - Only works in Razen before beta v0.1.75
filesystem[functionName](parameters);
```
This syntax is no longer supported in newer versions of Razen.
## Basic Examples
### Checking Path Existence
```razen
# Import the filesystem library
lib filesystem;
# Check if a file exists
bool fileExists = filesystem::exists("./data.txt");
show "File exists: " + fileExists;
# Check if a directory exists
bool dirExists = filesystem::exists("./documents");
show "Directory exists: " + dirExists;
```
### Creating Directories
```razen
# Import the filesystem library
lib filesystem;
# Create a directory
bool created = filesystem::create_dir("./my_documents");
show "Directory created: " + created;
# Create nested directories
bool nestedCreated = filesystem::create_dir("./my_documents/nested/folder");
show "Nested directories created: " + nestedCreated;
```
### Reading and Writing Files
```razen
# Import the filesystem library
lib filesystem;
# Write content to a file
# The third parameter (false) means don't append, overwrite if exists
bool written = filesystem::write_file("./hello.txt", "Hello, Razen Filesystem!", false);
show "File written: " + written;
# Read content from a file
str content = filesystem::read_file("./hello.txt");
show "File content: " + content;
# Append content to a file
bool appended = filesystem::append_file("./hello.txt", "\nThis is a new line.");
show "Content appended: " + appended;
# Read the updated content
str updatedContent = filesystem::read_file("./hello.txt");
show "Updated content: " + updatedContent;
```
### Checking File Types
```razen
# Import the filesystem library
lib filesystem;
# Check if path is a file
bool isFile = filesystem::is_file("./hello.txt");
show "Is file: " + isFile;
# Check if path is a directory
bool isDir = filesystem::is_dir("./my_documents");
show "Is directory: " + isDir;
```
### Copying and Moving Files
```razen
# Import the filesystem library
lib filesystem;
# Copy a file
bool copied = filesystem::copy("./hello.txt", "./my_documents/hello_copy.txt");
show "File copied: " + copied;
# Move a file
bool moved = filesystem::move("./hello.txt", "./my_documents/hello_moved.txt");
show "File moved: " + moved;
```
### Listing Directory Contents
```razen
# Import the filesystem library
lib filesystem;
# List directory contents
str contents = filesystem::list_dir("./my_documents");
show "Directory contents: " + contents;
# Check if specific files exist in the directory
for (num i = 0; i < contents.length; i = i + 1) {
show "Found: " + contents[i];
}
```
### Getting File Information
```razen
# Import the filesystem library
lib filesystem;
# Get file size
num size = filesystem::file_size("./my_documents/hello_copy.txt");
show "File size: " + size + " bytes";
# Get last modified time
num lastModified = filesystem::last_modified("./my_documents/hello_copy.txt");
show "Last modified timestamp: " + lastModified;
# Get file extension
str ext = filesystem::extension("./my_documents/hello_copy.txt");
show "File extension: " + ext;
# Get file stem (name without extension)
str stem = filesystem::file_stem("./my_documents/hello_copy.txt");
show "File stem: " + stem;
```
### Working with Paths
```razen
# Import the filesystem library
lib filesystem;
# Get parent directory
str parent = filesystem::parent_dir("./my_documents/nested/folder");
show "Parent directory: " + parent;
# Join path segments
str joined = filesystem::join_path(["my_documents", "nested", "file.txt"]);
show "Joined path: " + joined;
# Get absolute path
str absolute = filesystem::absolute_path("./my_documents");
show "Absolute path: " + absolute;
# Get current directory
str current = filesystem::current_dir();
show "Current directory: " + current;
```
### Creating Temporary Files and Directories
```razen
# Import the filesystem library
lib filesystem;
# Create a temporary file
str tempFile = filesystem::temp_file();
show "Temporary file created: " + tempFile;
# Write to the temporary file
filesystem::write_file(tempFile, "This is temporary content", false);
# Create a temporary directory
str tempDir = filesystem::temp_dir();
show "Temporary directory created: " + tempDir;
```
### Removing Files and Directories
```razen
# Import the filesystem library
lib filesystem;
# Remove a file
bool fileRemoved = filesystem::remove("./my_documents/hello_copy.txt");
show "File removed: " + fileRemoved;
# Remove a directory (and its contents)
bool dirRemoved = filesystem::remove("./my_documents/nested");
show "Directory removed: " + dirRemoved;
```
## Advanced Examples
### File Copy Utility
```razen
# Import the filesystem library
lib filesystem;
# Function to copy all files from one directory to another
fun copyDirectory(str sourceDir, str targetDir) {
# Check if source directory exists
if (!filesystem::exists(sourceDir) || !filesystem::is_dir(sourceDir)) {
return "Error: Source directory does not exist or is not a directory";
}
# Create target directory if it doesn't exist
if (!filesystem::exists(targetDir)) {
filesystem::create_dir(targetDir);
} else if (!filesystem::is_dir(targetDir)) {
return "Error: Target path exists but is not a directory";
}
# Get list of files in source directory
str files = filesystem::list_dir(sourceDir);
# Track statistics
num copied = 0;
num failed = 0;
# Copy each file
for (num i = 0; i < files.length; i = i + 1) {
str sourcePath = filesystem::join_path([sourceDir, files[i]]);
str targetPath = filesystem::join_path([targetDir, files[i]]);
# Only copy files, not directories
if (filesystem::is_file(sourcePath)) {
bool success = filesystem::copy(sourcePath, targetPath);
if (success) {
copied = copied + 1;
} else {
failed = failed + 1;
}
}
}
return "Copy complete. " + copied + " files copied, " + failed + " failed.";
}
# Test the copy directory function
show copyDirectory("./source_folder", "./backup_folder");
```
### File Search Utility
```razen
# Import the filesystem library
lib filesystem;
# Function to search for files with a specific extension
fun findFilesByExtension(str directory, str extension) {
# Check if directory exists
if (!filesystem::exists(directory) || !filesystem::is_dir(directory)) {
return "Error: Directory does not exist or is not a directory";
}
# Get list of files in directory
str files = filesystem::list_dir(directory);
# Filter files by extension
str matchingFiles = [];
for (num i = 0; i < files.length; i = i + 1) {
str filePath = filesystem::join_path([directory, files[i]]);
# Check if it's a file and has the right extension
if (filesystem::is_file(filePath) && filesystem::extension(filePath) == extension) {
matchingFiles.push(files[i]);
}
}
return matchingFiles;
}
# Test the file search function
str textFiles = findFilesByExtension("./documents", "txt");
show "Text files found: " + textFiles;
```
### File Backup Utility
```razen
# Import the filesystem library
lib filesystem;
# Function to create a backup of a file with timestamp
fun backupFile(str filePath) {
# Check if file exists
if (!filesystem::exists(filePath) || !filesystem::is_file(filePath)) {
return "Error: File does not exist or is not a file";
}
# Get current timestamp
num timestamp = Date.now();
# Get file components
str directory = filesystem::parent_dir(filePath);
str filename = filesystem::file_stem(filePath);
str extension = filesystem::extension(filePath);
# Create backup filename with timestamp
str backupFilename = filename + "_backup_" + timestamp + "." + extension;
str backupPath = filesystem::join_path([directory, backupFilename]);
# Copy the file to create backup
bool success = filesystem::copy(filePath, backupPath);
if (success) {
return "Backup created: " + backupPath;
} else {
return "Error: Failed to create backup";
}
}
# Test the backup function
show backupFile("./important_document.txt");
```
## Practical Application: Simple File Manager
```razen
# Import the filesystem library
lib filesystem;
# Simple file manager class
class FileManager {
# Constructor
init(str rootDirectory) {
this.rootDirectory = rootDirectory;
this.currentDirectory = rootDirectory;
# Create root directory if it doesn't exist
if (!filesystem::exists(rootDirectory)) {
filesystem::create_dir(rootDirectory);
}
}
# List files and directories in current directory
fun listContents() {
if (!filesystem::exists(this.currentDirectory)) {
return "Error: Current directory does not exist";
}
str contents = filesystem::list_dir(this.currentDirectory);
if (contents.length == 0) {
return "Directory is empty";
}
str result = "Contents of " + this.currentDirectory + ":\n";
for (num i = 0; i < contents.length; i = i + 1) {
str itemPath = filesystem::join_path([this.currentDirectory, contents[i]]);
if (filesystem::is_dir(itemPath)) {
result = result + "[DIR] " + contents[i] + "\n";
} else {
num size = filesystem::file_size(itemPath);
result = result + "[FILE] " + contents[i] + " (" + size + " bytes)\n";
}
}
return result;
}
# Change current directory
fun changeDirectory(str directory) {
# Handle special case for parent directory
if (directory == "..") {
# Don't go above root directory
if (this.currentDirectory == this.rootDirectory) {
return "Already at root directory";
}
this.currentDirectory = filesystem::parent_dir(this.currentDirectory);
return "Changed to " + this.currentDirectory;
}
# Handle absolute paths
str targetDir;
if (directory.startsWith("/") || directory.startsWith("./") || directory.startsWith("../")) {
targetDir = directory;
} else {
# Relative path
targetDir = filesystem::join_path([this.currentDirectory, directory]);
}
# Check if target directory exists
if (!filesystem::exists(targetDir) || !filesystem::is_dir(targetDir)) {
return "Error: Directory does not exist or is not a directory";
}
this.currentDirectory = targetDir;
return "Changed to " + this.currentDirectory;
}
# Create a new directory
fun createDirectory(str directoryName) {
str newDirPath = filesystem::join_path([this.currentDirectory, directoryName]);
if (filesystem::exists(newDirPath)) {
return "Error: Path already exists";
}
bool created = filesystem::create_dir(newDirPath);
if (created) {
return "Directory created: " + directoryName;
} else {
return "Error: Failed to create directory";
}
}
# Create a new file with content
fun createFile(str filename, str content) {
str filePath = filesystem::join_path([this.currentDirectory, filename]);
if (filesystem::exists(filePath)) {
return "Error: File already exists";
}
bool created = filesystem::write_file(filePath, content, false);
if (created) {
return "File created: " + filename;
} else {
return "Error: Failed to create file";
}
}
# Read a file
fun readFile(str filename) {
str filePath = filesystem::join_path([this.currentDirectory, filename]);
if (!filesystem::exists(filePath) || !filesystem::is_file(filePath)) {
return "Error: File does not exist or is not a file";
}
str content = filesystem::read_file(filePath);
return "Contents of " + filename + ":\n" + content;
}
# Delete a file or directory
fun delete(str name) {
str path = filesystem::join_path([this.currentDirectory, name]);
if (!filesystem::exists(path)) {
return "Error: Path does not exist";
}
bool removed = filesystem::remove(path);
if (removed) {
if (filesystem::is_dir(path)) {
return "Directory deleted: " + name;
} else {
return "File deleted: " + name;
}
} else {
return "Error: Failed to delete";
}
}
# Get current working directory
fun getCurrentDirectory() {
return "Current directory: " + this.currentDirectory;
}
}
# Create a file manager instance
FileManager manager = new FileManager("./file_manager_root");
# Demonstrate file manager operations
show manager.getCurrentDirectory();
show manager.createDirectory("documents");
show manager.createDirectory("images");
show manager.listContents();
show manager.changeDirectory("documents");
show manager.getCurrentDirectory();
show manager.createFile("notes.txt", "This is a test file.\nIt contains multiple lines.\nCreated by Razen File Manager.");
show manager.listContents();
show manager.readFile("notes.txt");
show manager.changeDirectory("..");
show manager.getCurrentDirectory();
show manager.listContents();
```
## Summary
The Filesystem Library in Razen provides essential functions for working with files and directories:
- File operations: `read_file`, `write_file`, `append_file`, `copy`, `move`, `remove`
- Directory operations: `create_dir`, `list_dir`, `remove`
- Path operations: `join_path`, `parent_dir`, `absolute_path`, `current_dir`
- Information functions: `exists`, `is_file`, `is_dir`, `file_size`, `last_modified`, `extension`, `file_stem`
- Temporary file/directory creation: `temp_file`, `temp_dir`
These functions help you work with the file system efficiently in your Razen programs.