C - プロセスとシステムサービス - 限界を超える - system関数, コマンド
Head First C ―頭とからだで覚えるCの基本、 David Griffiths(著)、 Dawn Griffiths(著)、 中田 秀基(監修)、 木下 哲也(翻訳)、 O’Reilly Media)の 9章(プロセスとシステムサービス - 限界を超える)、p.378(長いエクササイズ)の解答を求めてみる。
Makefile
all: main.c
cc main.c && ./a.out
コード
main.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
char *now()
{
time_t t;
time(&t);
return asctime(localtime(&t));
}
int main()
{
char comment[80];
char cmd[120];
fgets(comment, 80, stdin);
sprintf(cmd, "echo '%s %s' >> reports.log", comment, now());
system(cmd);
}
入出力結果(Terminal, Zsh)
% make
cc main.c && ./a.out
Hello, World! 日本語
% cat reports.log
Hello, World! 日本語
Mon Feb 24 17:24:44 2025
% make
cc main.c && ./a.out
python
% cat reports.log
Hello, World! 日本語
Mon Feb 24 17:24:44 2025
python
Mon Feb 24 17:25:41 2025
%