Unix/Linuxプログラミング 理論と実践 第2章(プログラミング課題) つづき2
備忘録です.
環境:FreeBSD 8.2-STABLE
書籍:Unix/Linuxプログラミング理論と実践
cpコマンドの-iオプションはどう実装されているのか,という話.
man を読んでみる
cpコマンドのmanで-iオプションを探す.
-i Cause cp to write a prompt to the standard error output before copying a file that would overwrite an existing file. If the response from the standard input begins with the character ‘y’ or ‘Y’, the file copy is attempted. (The -i option overrides any pre‐ vious -f or -n options.)
cp -i を実行してみる
manで調べたとおり,上書きをすることについて,yesかnoかを聞かれる.
$ cp -i file1 file2 overwrite file2? (y/n [n])
ソースコード調査
cp.cのl.389で,stat()により,コピー先ファイルの情報取得を試みる.
もし,ファイルが存在すれば,変数dneに0が入る.
if (stat(to.p_path, &to_stat) == -1) dne = 1; else { 中略 dne = 0; }
もし,dneが偽で(utils.cのl.101),変数iflagが真なら(同l.108),確認メッセージが出る(同l.109).
if (!dne) { #define YESNO "(y/n [n]) " 中略 } else if (iflag) { (void)fprintf(stderr, "overwrite %s? %s", to.p_path, YESNO); checkch = ch = getchar(); while (ch != '\n' && ch != EOF) ch = getchar(); if (checkch != 'y' && checkch != 'Y') { (void)close(from_fd); (void)fprintf(stderr, "not overwritten\n"); return (1); } }