開発環境
- OS X Lion - Apple(OS)
- TextWrangler(Text Editor) (BBEditの無料、light版)
- 言語: C
- コンパイラ: UNIX ccコンパイラ (汎用UNIX)
『実践プログラミング 第3版』 (Steve Oualline (著)、 望月 康司 (監修) (翻訳)、 谷口 功 (翻訳)、 オライリー・ジャパン、1998年、ISBN978-4900900646) の14章(ファイル入出力)14.10(プログラミング実習)実習14-2を解いてみる。
実習14-2.
コード(TextWrangler)
#include <stdio.h> #include <stdlib.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 sample.c sample.out $ cat sample.out #include <stdio.h> #include <stdlib.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 コメント:
コメントを投稿