9

File I/O

Reading and writing files with Odi domain

?? Not Available in Playground

File operations require filesystem access and won't work in the browser playground. Run these examples locally with ifa run.

Odi Methods

Method Description
read(path) Read file contents as string
write(path, data) Write string to file (overwrites)
append(path, data) Append to file
exists(path) Check if file exists
delete(path) Delete a file
list(dir) List directory contents
mkdir(path) Create directory

Reading Files

// Read entire file as string
ayanmo content = Odi.read("config.txt");
Irosu.fo(content);

// Read and process line by line
ayanmo content = Odi.read("data.txt");
ayanmo lines = Ika.split(content, "\n");

fun line ninu lines {
    Irosu.fo("Line: " + line);
}

Writing Files

// Write text to file (creates or overwrites)
Odi.write("output.txt", "Hello, Ifá!");

// Write multiple lines
ayanmo lines = ["Line 1", "Line 2", "Line 3"];
ayanmo content = Ika.join(lines, "\n");
Odi.write("multiline.txt", content);

// Append to existing file
Odi.append("log.txt", "New log entry\n");

Checking Files

// Check before reading
ti (Odi.exists("config.txt")) {
    ayanmo config = Odi.read("config.txt");
    Irosu.fo("Config loaded");
} bib?k? {
    Irosu.fo("Config file not found, using defaults");
}

Directory Operations

// Create directory
Odi.mkdir("output");

// List directory contents
ayanmo files = Odi.list(".");
fun file ninu files {
    Irosu.fo("Found: " + file);
}

// Delete file
ti (Odi.exists("temp.txt")) {
    Odi.delete("temp.txt");
}

Practical Example: Config File

// config.txt format:
// key=value
// key2=value2

ise load_config(path) {
    ayanmo config = {};
    
    ti (Odi.exists(path)) {
        ayanmo content = Odi.read(path);
        ayanmo lines = Ika.split(content, "\n");
        
        fun line ninu lines {
            ti (Ika.contains(line, "=")) {
                ayanmo parts = Ika.split(line, "=");
                ayanmo key = Ogunda.get(parts, 0);
                ayanmo value = Ogunda.get(parts, 1);
                // Store in config map
                Irosu.fo(key + " = " + value);
            }
        }
    }
    
    padap? config;
}

load_config("app.config");

Error Handling with Files

// Safe file reading
ise safe_read(path) {
    ti (!Odi.exists(path)) {
        Irosu.kigbe("File not found: " + path);
        padap? nil;
    }
    padap? Odi.read(path);
}

ayanmo data = safe_read("data.txt");
ti (data != nil) {
    Irosu.fo("Read " + Ika.len(data) + " characters");
}