Wednesday, July 12, 2017

[Matlab] Create a log file using 'fopen', 'fprintf', and 'fclose'

A log file is often required to write warnings, errors, and etc while running a simulation, so we can know what has happened during the simulation.
Let's see how to create a log file with Matlab.

----------------------------------------------
% Variables and data
variable = {'engine','tm','driver'};
data = [1, 2, 3;4, 5, 6;7, 8, 9];

% Path
path =[pwd,'\Configuration'];
name = 'log.txt';
file = fullfile(path,name);
[fid,msg] = fopen(file,'w+'); % 'w+' open a file for adding to end line
if fid == -1
    error(msg);
else
    % Start date and time
    sStart = clock;
    sStart = sprintf('%d%s%d%s%d%s%d%s%d%s',sStart(1),'-',sStart(2),'-',...
        sStart(3),', ',sStart(4),'h',sStart(5),'m');
    fprintf(fid,'%s%s\n','Start : ',sStart);
 
    % Write variables
    for N=1:1:length(variable)
        if N < length(variable)
            fprintf(fid,'%s\t\t',variable{N});
        elseif N == length(variable)
            fprintf(fid,'%s\n',variable{N});
        end
     
    end
 
    fprintf(fid,'%d\t\t%d\t\t%d\n',data);
 
    % End date and time
    sEnd = clock;
    sEnd = sprintf('%d%s%d%s%d%s%d%s%d%s',sEnd(1),'-',sEnd(2),'-',sEnd(3),...
        ', ',sEnd(4),'h',sEnd(5),'m');
    fprintf(fid,'%s%s\n','End : ',sEnd);
end
fclose(fid);
--------------------------------------------------

As a result of the code above, the following log is created.
------------------------------------
Start : 2017-7-13, 10h33m
engine tm driver
1 4 7
2 5 8
3 6 9
End : 2017-7-13, 10h33m
---------------------------------------

% fopen option
FID = fopen(FILENAME,PERMISSION) opens the file FILENAME in the
    mode specified by PERMISSION:
 
        'r'     open file for reading
        'w'     open file for writing; discard existing contents
        'a'     open or create file for writing; append data to end of file
        'r+'    open (do not create) file for reading and writing
        'w+'    open or create file for reading and writing; discard
                existing contents
        'a+'    open or create file for reading and writing; append data
                to end of file
        'W'     open file for writing without automatic flushing
        'A'     open file for appending without automatic flushing


No comments:

Post a Comment