開発環境
- OS X Lion - Apple(OS)
- Emacs、BBEdit - Bare Bones Software, Inc. (Text Editor)
- プログラミング言語: C
- Clang (コンパイラ)
プログラミング言語C 第2版 ANSI規格準拠 (B.W. カーニハン D.M. リッチー (著)、 石田 晴久 (翻訳)、共立出版)の第7章(入出力)、7.5(ファイル・アクセス)、7.6(エラー処理 - Stderr と Exit)、7.7(行の入出力)、演習7-8を解いてみる。
その他参考書籍
- プログラミング言語Cアンサー・ブック 第2版 (クロビス・L.トンド、スコット・E.ギンペル(著)、矢吹 道郎(翻訳))
演習 7-8.
コード
sample.c
#include <stdio.h> #define MAXLINE 1000 int main(int argc, char *argv[]) { char line[MAXLINE]; FILE *fp; int n = 0; while (--argc > 0) { if ((fp = fopen(*++argv, "r")) != NULL) { if (n != 0) { printf("\f"); } n++; printf("ファイル名: %s, ページ番号: %d\n", *argv, n); while (fgets(line, MAXLINE, fp) != NULL) { printf("%s", line); } } else { fprintf(stderr, "can't open %s\n", *argv); exit(0); } } return 0; }
入出力結果(Terminal)
$ ./a.out sample.txt sample.c ファイル名: sample.txt, ページ番号: 1 Ah Love! could you and I with Fate conspire To grasp this sorry Scheme of Things entire, Would not we shatter it to bits -- and then Re-mould it nearer to the Heart's Desire! ah love! could you and i with fate conspire to grasp this sorry scheme of things entire, would not we shatter it to bits -- and then re-mould it nearer to the heart's desire! 1 5 2 4 3 !@#$%Ah Love! could you and I with Fate conspire !@#$%To grasp this sorry Scheme of Things entire, !@#$%Would not we shatter it to bits -- and then !@#$%Re-mould it nearer to the Heart's Desire! !@#$%ah love! could you and i with fate conspire !@#$%to grasp this sorry scheme of things entire, !@#$%would not we shatter it to bits -- and then !@#$%re-mould it nearer to the heart's desire! ファイル名: sample.c, ページ番号: 2 #include <stdio.h> #define MAXLINE 1000 int main(int argc, char *argv[]) { char line[MAXLINE]; FILE *fp; int n = 0; while (--argc > 0) { if ((fp = fopen(*++argv, "r")) != NULL) { if (n != 0) { printf("\f"); } n++; printf("ファイル名: %s, ページ番号: %d\n", *argv, n); while (fgets(line, MAXLINE, fp) != NULL) { printf("%s", line); } } else { fprintf(stderr, "can't open %s\n", *argv); exit(0); } } return 0; } $
0 コメント:
コメントを投稿