開発環境
- OS X Mavericks - Apple(OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- C (プログラミング言語)
- Clang (コンパイラ)
C実践プログラミング 第3版 (Steve Oualline (著)、 望月 康司 (監訳) (翻訳)、谷口 功 (翻訳)、オライリー・ジャパン)のⅡ部(単純なプログラミング)の14章(ファイル入出力)、14.1(ファイル関数)、14.2(変換ルーチン)、14.3(バイナリファイルとASCIIファイル)、14.4(行終端にまつわる謎)、14.5(バイナリI/O)、14.6(バッファリングの問題)、14.7(バッファリングを行わないI/O)、14.8(ファイル形式の設計)、14.10(プログラミング実習)、実習 14-5を解いてみる。
その他参考書籍
- プログラミング言語C 第2版 ANSI規格準拠 (B.W. カーニハン D.M. リッチー (著)、 石田 晴久 (翻訳)、共立出版)
- プログラミング言語Cアンサー・ブック 第2版 (クロビス・L.トンド、スコット・E.ギンペル(著)、矢吹 道郎(翻訳))
実習14-5.
コード
temp.c
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char ch = 0;
FILE *out_file;
out_file = fopen("temp.txt", "w");
if (out_file == NULL){
fprintf(stderr, "Cannot open %s\n", argv[2]);
exit (8);
}
do{
fputc(ch, out_file);
ch++;
} while (ch != 0);
return (0);
}
コード
sample.c
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char ch;
FILE *in_file;
FILE *out_file;
if (argc != 3){
fprintf(stderr, "Error: Wrong number of arguments\n");
fprintf(stderr, "Usage is: sample <from> <to>\n");
exit (8);
}
in_file = fopen(argv[1], "r");
if (in_file == NULL){
fprintf(stderr, "Cannot open %s\n", argv[1]);
exit (8);
}
out_file = fopen(argv[2], "wb");
if (out_file == NULL){
fprintf(stderr, "Cannot open %s\n", argv[2]);
exit (8);
}
while (1){
ch = fgetc(in_file);
if (ch == EOF){
break;
}
if ((ch & 0x80) == 0){
fputc(ch, out_file);
}
}
fclose(in_file);
fclose(out_file);
return (0);
}
makefile
CC=cc CFLAGS=-g sample: sample.c $(CC) $(CFLAGS) -o sample sample.c clean: rm -f sample
入出力結果(Terminal)
$ cc -g -o temp temp.c
$ cat temp.txt
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????$ make
cc -g -o sample sample.c
$ ./sample temp.txt temp.txt.out
$ cat temp.txt.out
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~$
0 コメント:
コメントを投稿