sal/rhaiexamples/02_file_operations.rhai
2025-04-04 18:38:53 +02:00

64 lines
1.9 KiB
Plaintext

// 02_file_operations.rhai
// Demonstrates file system operations using SAL
// Create a test directory
let test_dir = "rhai_test_dir";
println(`Creating directory: ${test_dir}`);
let mkdir_result = mkdir(test_dir);
println(`Directory creation result: ${mkdir_result}`);
// Check if the directory exists
let dir_exists = exist(test_dir);
println(`Directory exists: ${dir_exists}`);
// Create a test file
let test_file = test_dir + "/test_file.txt";
let file_content = "This is a test file created by Rhai script.";
// Create the file using a different approach
println(`Creating file: ${test_file}`);
// First ensure the directory exists
run_command(`mkdir -p ${test_dir}`);
// Then create the file using a simpler approach
// First touch the file
let touch_cmd = `touch ${test_file}`;
run_command(touch_cmd);
// Then write to it with a separate command
let echo_cmd = `echo ${file_content} > ${test_file}`;
let write_result = run_command(echo_cmd);
println(`File creation result: ${write_result.success}`);
// Wait a moment to ensure the file is created
run_command("sleep 1");
// Check if the file exists
let file_exists = exist(test_file);
println(`File exists: ${file_exists}`);
// Get file size
if file_exists {
let size = file_size(test_file);
println(`File size: ${size} bytes`);
}
// Copy the file
let copied_file = test_dir + "/copied_file.txt";
println(`Copying file to: ${copied_file}`);
let copy_result = copy(test_file, copied_file);
println(`File copy result: ${copy_result}`);
// Find files in the directory
println("Finding files in the test directory:");
let files = find_files(test_dir, "*.txt");
for file in files {
println(` - ${file}`);
}
// Clean up (uncomment to actually delete the files)
// println("Cleaning up...");
// delete(copied_file);
// delete(test_file);
// delete(test_dir);
// println("Cleanup complete");
"File operations script completed successfully!"