C - 小さなツールの作成 - 1つのことだけをうまくやる - 標準出力, 標準エラー(stdout, stderr)
Head First C ―頭とからだで覚えるCの基本、 David Griffiths(著)、 Dawn Griffiths(著)、 中田 秀基(監修)、 木下 哲也(翻訳)、 O’Reilly Media)の 3章(小さなツールの作成 - 1つのことだけをうまくやる)、p.125(極秘)の解答を求めてみる。
コード
main.c
#include <stdio.h>
int main()
{
char word[10];
int i = 0;
// message1.txt
// the
// submarine
// will
// surface
// at
// nine
// pm
// message2.txt
// buy
// six
// eggs
// and
// some
// milk
while (scanf("%9s", word) == 1)
{
i++;
if (i % 2)
{
fprintf(stdout, "%s\n", word);
}
else
{
fprintf(stderr, "%s\n", word);
}
}
}
入出力結果(Terminal, Zsh)
% cc main.c -o secret_messages
% ./secret_messages < secret.txt > message1.txt 2> message2.txt
% cat message1.txt
the
submarine
will
surface
at
nine
pm
% cat message2.txt
buy
six
eggs
and
some
milk
%