開発環境
- OS X Lion - Apple(OS)
- TextWrangler(Text Editor) (BBEditの無料、light版)
- 言語: C
- コンパイラ: UNIX ccコンパイラ (汎用UNIX)
『実践プログラミング 第3版』 (Steve Oualline (著)、 望月 康司 (監修) (翻訳)、 谷口 功 (翻訳)、 オライリー・ジャパン、1998年、ISBN978-4900900646) の14章(ファイル入出力)14.7(バッファリングを行わないI/O)設問14-3を解いてみる。
設問14-3.
openの後のファイルが上手く開けたかどうか判定するif文のブロックのfprintfの第1引数がフォーマット文字列になってるからエラーメッセージが出力、表示されずにコアダンプが行われる。ということで、第1引数にstderrを指定するように修正。
修正。
コード(TextWrangler)
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #ifndef O_BINARY #define O_BINARY 0 #endif /* O_BINARY */ #define BUFFER_SIZE (16 * 1024) int main(int argc, char *argv[]) { char buffer[BUFFER_SIZE]; int in_file; int out_file; int read_size; if(argc != 3){ fprintf(stderr, "Error:Wrong Number of arguments\n"); fprintf(stderr, "Usage is: copy <from> <to>\n"); exit(8); } in_file = open(argv[1],O_RDONLY|O_BINARY); if(in_file <0){ fprintf(stderr, "Error:Unable to open %s\n", argv[1]); exit(8); } out_file = open(argv[2],O_WRONLY|O_TRUNC|O_CREAT|O_BINARY, 0666); if(out_file < 0){ fprintf(stderr, "Error:Unable to open %s\n", argv[2]); exit(8); } while (1){ read_size = read(in_file,buffer,sizeof(buffer)); if(read_size == 0){ break; } if(read_size <0){ fprintf(stderr, "Error:Read error\n"); exit(8); } write(out_file, buffer, (unsigned int) read_size); } close(in_file); close(out_file); return (0); }
入出力結果(Terminal)
$ cc -g -o sample sample.c $ ./sample Error:Wrong Number of arguments Usage is: copy <from> <to> $ ./sample sample.pl sample.out Error:Unable to open sample.pl $ ./sample sample.c sample.out $ cat sample.out #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #ifndef O_BINARY #define O_BINARY 0 #endif /* O_BINARY */ #define BUFFER_SIZE (16 * 1024) int main(int argc, char *argv[]) { char buffer[BUFFER_SIZE]; int in_file; int out_file; int read_size; if(argc != 3){ fprintf(stderr, "Error:Wrong Number of arguments\n"); fprintf(stderr, "Usage is: copy <from> <to>\n"); exit(8); } in_file = open(argv[1],O_RDONLY|O_BINARY); if(in_file <0){ fprintf(stderr, "Error:Unable to open %s\n", argv[1]); exit(8); } out_file = open(argv[2],O_WRONLY|O_TRUNC|O_CREAT|O_BINARY, 0666); if(out_file < 0){ fprintf(stderr, "Error:Unable to open %s\n", argv[2]); exit(8); } while (1){ read_size = read(in_file,buffer,sizeof(buffer)); if(read_size == 0){ break; } if(read_size <0){ fprintf(stderr, "Error:Read error\n"); exit(8); } write(out_file, buffer, (unsigned int) read_size); } close(in_file); close(out_file); return (0); }$
0 コメント:
コメントを投稿