Directories in Scilab
Here’s the translation of the Go code to Scilab, formatted in Markdown suitable for Hugo:
Our program demonstrates working with directories in Scilab. Here’s the full source code:
function check(e)
if e ~= 0 then
error(lasterror());
end
endfunction
// Create a new sub-directory in the current working directory
[status, msg] = mkdir('subdir');
check(status);
// Helper function to create a new empty file
function createEmptyFile(name)
fd = mopen(name, 'w');
mclose(fd);
endfunction
createEmptyFile('subdir/file1');
// Create a hierarchy of directories, including parents
[status, msg] = mkdir('subdir/parent/child');
check(status);
createEmptyFile('subdir/parent/file2');
createEmptyFile('subdir/parent/file3');
createEmptyFile('subdir/parent/child/file4');
// List directory contents
disp('Listing subdir/parent');
files = listfiles('subdir/parent');
for i = 1:size(files, '*')
[path, fname, extension] = fileparts(files(i));
isdir = isdir(files(i));
disp([' ', fname, extension, ' ', string(isdir)]);
end
// Change the current working directory
cd('subdir/parent/child');
// Now we'll see the contents of subdir/parent/child
disp('Listing subdir/parent/child');
files = listfiles('.');
for i = 1:size(files, '*')
[path, fname, extension] = fileparts(files(i));
isdir = isdir(files(i));
disp([' ', fname, extension, ' ', string(isdir)]);
end
// Change back to where we started
cd('../../..');
// Visit a directory recursively
disp('Visiting subdir');
function visit(path)
files = listfiles(path);
for i = 1:size(files, '*')
disp([' ', files(i), ' ', string(isdir(files(i)))]);
if isdir(files(i)) then
visit(files(i));
end
end
endfunction
visit('subdir');
// Clean up
rmdir('subdir', 's');
Let’s break down the key parts of this script:
We start by defining a
check
function to handle errors.We use
mkdir
to create directories. Scilab doesn’t have a direct equivalent toMkdirAll
, so we create the nested directories separately.The
createEmptyFile
function creates an empty file usingmopen
andmclose
.We use
listfiles
to get the contents of a directory. This is similar toReadDir
in the original example.cd
is used to change the current working directory, just like in the original.The
visit
function recursively visits all subdirectories. This is our equivalent ofWalkDir
.Finally, we use
rmdir
with the ’s’ option to remove the entire directory tree we created.
To run this script, save it as directories.sce
and execute it in Scilab:
--> exec('directories.sce', -1)
Listing subdir/parent
child TRUE
file2 FALSE
file3 FALSE
Listing subdir/parent/child
file4 FALSE
Visiting subdir
subdir TRUE
subdir/file1 FALSE
subdir/parent TRUE
subdir/parent/child TRUE
subdir/parent/child/file4 FALSE
subdir/parent/file2 FALSE
subdir/parent/file3 FALSE
This script demonstrates basic directory operations in Scilab, including creating directories, listing contents, changing the current directory, and recursively visiting a directory tree.