68 lines
2.3 KiB
Plaintext
68 lines
2.3 KiB
Plaintext
// 06_file_read_write.rhai
|
|
// Demonstrates file read and write operations using SAL
|
|
|
|
// Create a test directory
|
|
let test_dir = "rhai_file_test_dir";
|
|
println(`Creating directory: ${test_dir}`);
|
|
let mkdir_result = mkdir(test_dir);
|
|
println(`Directory creation result: ${mkdir_result}`);
|
|
|
|
// Define file paths
|
|
let test_file = test_dir + "/test_file.txt";
|
|
let append_file = test_dir + "/append_file.txt";
|
|
|
|
// 1. Write to a file
|
|
println(`\n--- Writing to file: ${test_file} ---`);
|
|
let content = "This is the first line of text.\nThis is the second line of text.";
|
|
let write_result = file_write(test_file, content);
|
|
println(`Write result: ${write_result}`);
|
|
|
|
// 2. Read from a file
|
|
println(`\n--- Reading from file: ${test_file} ---`);
|
|
let read_content = file_read(test_file);
|
|
println("File content:");
|
|
println(read_content);
|
|
|
|
// 3. Append to a file
|
|
println(`\n--- Creating and appending to file: ${append_file} ---`);
|
|
// First create the file with initial content
|
|
let initial_content = "Initial content - line 1\nInitial content - line 2\n";
|
|
let create_result = file_write(append_file, initial_content);
|
|
println(`Create result: ${create_result}`);
|
|
|
|
// Now append to the file
|
|
let append_content = "Appended content - line 3\nAppended content - line 4\n";
|
|
let append_result = file_write_append(append_file, append_content);
|
|
println(`Append result: ${append_result}`);
|
|
|
|
// Read the appended file to verify
|
|
println(`\n--- Reading appended file: ${append_file} ---`);
|
|
let appended_content = file_read(append_file);
|
|
println("Appended file content:");
|
|
println(appended_content);
|
|
|
|
// 4. Demonstrate multiple appends
|
|
println(`\n--- Demonstrating multiple appends ---`);
|
|
for i in range(1, 4) {
|
|
// Get timestamp and ensure it's properly trimmed
|
|
let result = run("date");
|
|
let timestamp = result.stdout.trim();
|
|
println(`Timestamp: ${timestamp}`);
|
|
let log_entry = `Log entry #${i} at ${timestamp}\n`;
|
|
file_write_append(append_file, log_entry);
|
|
println(`Added log entry #${i}`);
|
|
}
|
|
|
|
// Read the final file content
|
|
println(`\n--- Final file content after multiple appends ---`);
|
|
let final_content = file_read(append_file);
|
|
println(final_content);
|
|
|
|
// Clean up (uncomment to actually delete the files)
|
|
// println("\nCleaning up...");
|
|
// delete(test_file);
|
|
// delete(append_file);
|
|
// delete(test_dir);
|
|
// println("Cleanup complete");
|
|
|
|
"File read/write operations script completed successfully!" |