Nyx by Example

File Read & Write

Nyx provides built-in functions write_file and read_file for simple file I/O without any import. Writing a file is a single call; reading it back returns the full contents as a String. This example also shows str_byte_length, which counts raw bytes rather than characters.

Code

// Escribir y leer un archivo: write_file, read_file

fn main() -> int {
    let path: String = "/tmp/nyx_example_11.txt"
    let contenido: String = "Hola desde Nyx!\nSegunda línea.\nTercera línea."

    // Escribir el archivo
    write_file(path, contenido)
    print("Archivo escrito en: " + path)

    // Leer el archivo
    let leido: String = read_file(path)
    print("Contenido leido:")
    print(leido)

    // Verificar longitud
    print("Bytes: " + int_to_string(str_byte_length(leido)))

    return 0
}

Output

Archivo escrito en: /tmp/nyx_example_11.txt
Contenido leido:
Hola desde Nyx!
Segunda línea.
Tercera línea.
Bytes: 47

Explanation

write_file(path, content) creates or overwrites the file at path with the given string. Newline characters (\n) embedded in the string become actual line breaks in the file. There is no need to open or close a file handle — the function handles everything internally.

read_file(path) reads the entire file and returns its contents as a single String. For large files you would use streaming I/O from std/io, but for most scripts this one-shot approach is perfectly sufficient.

str_byte_length returns the number of bytes in a UTF-8 encoded string, which may differ from the number of Unicode code points. This is useful when you care about storage size rather than character count.

← Previous Next →

Source: examples/by-example/11-file-read-write.nx