LoginSignup
1
1

More than 5 years have passed since last update.

system関数でログファイルの作成

Posted at

計算結果などを随時ログファイルに残しておきたいということを考える.

fopen~textscanなどでワークスペースにログファイルを入れたり出したりしてもいいが,system関数で(普段ターミナルでやってるように)ログを書き込むのが楽で良い.

addlog.m
function [  ] = addlog( path, log, mode )
%ADDLOG create and add a log using system commands

if(nargin<2)
    mode='add'; %書き込みモード(add か newか.この辺は適当)
end

m=[];
if(strcmp(mode, 'new'))
    m=sprintf('system(\''echo %s [`date`] > %s\'')', log, path); 
% このようにsystem関数内でechoやdateといったコマンドが利用できる.
% しかもsprintfを用いることでmatlabの変数を渡すことも可能.
elseif(strcmp(mode, 'add'))
    m=sprintf('system(\''echo %s [`date`] >> %s\'')', log, path);
end
fprintf('%s\n', m);
eval(m);

end

実行するとこんな感じ

>> addlog('log.txt', 'file created', 'new')
system('echo file created [`date`] > log.txt')

ans =

     0

>> system('cat log.txt')
file created [Wed Dec 12 09:41:32 JST 2012]

ans =

     0

>> addlog('log.txt', 'new line', 'add')
system('echo new line [`date`] >> log.txt')

ans =

     0

>> system('cat log.txt')
file created [Wed Dec 12 09:41:32 JST 2012]
new line [Wed Dec 12 09:41:51 JST 2012]

ans =

     0
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1