This program demonstrates how to write data to a file, read data from a file, and handle file closing in Scilab.
Step 1: Writing to a File
// Open the file for writing ('w')
fileID = fopen('example.txt', 'w');
// Check if the file was opened successfully
if fileID == -1 then
disp('Error opening file for writing');
else
// Write some data to the file
fprintf(fileID, 'This is a test message written to the file.\n');
fprintf(fileID, 'Scilab file handling example.\n');
// Close the file
fclose(fileID);
disp('Data written to the file successfully.');
end
Step 2: Reading from a File
// Open the file for reading ('r')
fileID = fopen('example.txt', 'r');
// Check if the file was opened successfully
if fileID == -1 then
disp('Error opening file for reading');
else
// Read the data from the file line by line
while %t
line = fgets(fileID); // Read one line
if line == -1 then
break; // End of file
end
disp(line); // Display the line
end
// Close the file
fclose(fileID);
disp('Data read from the file successfully.');
end
Explanation:
fopen('filename', 'mode'): Opens a file. The mode can be:
'r' for reading,
'w' for writing,
'a' for appending.
fprintf(fileID, 'text'): Writes formatted text to the file.
fgets(fileID): Reads one line of text from the file.
fclose(fileID): Closes the file when you're done with it.
Error Handling:
The program checks if the file is opened successfully by verifying the return value of fopen.
If it returns -1, there was an error opening the file.
If the file opens successfully, the operations (writing or reading) are performed.