Writing Files in Scilab

Here’s the translation of the Go code to Scilab, formatted in Markdown suitable for Hugo:

Writing files in Scilab follows similar patterns to the ones we saw earlier for reading.

// To start, here's how to dump a string (or just bytes) into a file.
d1 = "hello" + ascii(10) + "scilab" + ascii(10);
mputl(d1, "/tmp/dat1");

// For more granular writes, open a file for writing.
fd = mopen("/tmp/dat2", "w");

// It's good practice to close the file when you're done with it.
function cleanup()
    mclose(fd);
endfunction

try
    // You can write byte arrays as you'd expect.
    d2 = [115 111 109 101 10];
    n2 = mput(d2, "c", fd);
    printf("wrote %d bytes\n", n2);

    // A string write is also available.
    n3 = mput("writes" + ascii(10), "c", fd);
    printf("wrote %d bytes\n", n3);

    // Scilab doesn't have a direct equivalent to Go's Sync(),
    // but you can flush the file buffer to ensure writes are applied.
    mflush(fd);

    // Scilab doesn't have a built-in buffered writer,
    // but you can implement a simple one using a string buffer.
    buffer = "";
    buffer = buffer + "buffered" + ascii(10);
    n4 = mput(buffer, "c", fd);
    printf("wrote %d bytes\n", n4);

    // Flush the buffer to ensure all operations have been applied.
    mflush(fd);
catch
    disp("An error occurred while writing to the file.");
end

// Call the cleanup function to close the file.
cleanup();

Try running the file-writing code.

--> exec writing-files.sce
wrote 5 bytes
wrote 7 bytes
wrote 9 bytes

Then check the contents of the written files.

$ cat /tmp/dat1
hello
scilab

$ cat /tmp/dat2
some
writes
buffered

Next, we’ll look at applying some of the file I/O ideas we’ve just seen to the standard input and output streams.