Reading Files in Scilab

Our first example demonstrates reading files in Scilab. Reading files is a basic task needed for many Scilab programs. Let’s look at some examples of reading files.

// Helper function to check for errors
function check(e)
    if e ~= 0 then
        error(msgerr(e));
    end
endfunction

// Reading the entire file content
[fd, err] = mopen('/tmp/dat', 'r');
check(err);
content = mgetl(fd);
mclose(fd);
disp(content);

// Reading specific parts of a file
[fd, err] = mopen('/tmp/dat', 'r');
check(err);

// Read 5 bytes from the beginning of the file
b1 = mget(5, 'c', fd);
disp(msprintf('%d bytes: %s', length(b1), ascii(b1)));

// Seek to a specific position and read
mseek(6, fd);
b2 = mget(2, 'c', fd);
disp(msprintf('%d bytes @ %d: %s', length(b2), 6, ascii(b2)));

// Seek relative to current position
mseek(4, fd, 'cur');

// Seek relative to end of file
mseek(-10, fd, 'end');

// Read at least 2 bytes
mseek(6, fd, 'set');
b3 = mget(2, 'c', fd);
disp(msprintf('%d bytes @ %d: %s', length(b3), 6, ascii(b3)));

// Rewind to the beginning of the file
mseek(0, fd);

// Using mgetstr for buffered reading
b4 = mgetstr(5, fd);
disp(msprintf('5 bytes: %s', b4));

mclose(fd);

To run this script, save it as reading_files.sce and execute it in Scilab:

--> exec('reading_files.sce')

Before running the script, create a test file:

$ echo "hello" > /tmp/dat
$ echo "scilab" >> /tmp/dat

The output will depend on the content of the file, but it should be similar to:

hello
scilab
5 bytes: hello
2 bytes @ 6: sc
2 bytes @ 6: sc
5 bytes: hello

Note that Scilab doesn’t have an exact equivalent to Go’s bufio package, but the mgetstr function provides similar functionality for reading strings from a file.

Also, Scilab uses 1-based indexing, unlike Go which uses 0-based indexing. This affects how we calculate file positions when seeking.

Next, we’ll look at writing files in Scilab.