Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

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

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
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away