開発環境
- OS X Lion - Apple(OS)
- TextWrangler(Text Editor) (BBEditの無料、light版)
- 言語: C
- コンパイラ: UNIX ccコンパイラ (汎用UNIX)
『実践プログラミング 第3版』 (Steve Oualline (著)、 望月 康司 (監修) (翻訳)、 谷口 功 (翻訳)、 オライリー・ジャパン、1998年、ISBN978-4900900646) II部(単純なプログラミング)の14章(ファイルの入出力)14.10(プログラミング実習/O)実習14-3を解いてみる。
実習14-3.
コード(TextWrangler)
sample.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
FILE *in_file;
FILE *out_file1;
FILE *out_file2;
int ch;
char name[100];
char name1[100];
char name2[100];
printf("数値リストが記述されているファイル名を入力: ");
fgets(name,sizeof(name),stdin);
name[strlen(name) - 1] = '\0';
in_file = fopen(name, "r");
if(in_file == NULL){
fprintf(stderr, "Cannot open %s\n", name);
exit(8);
}
strcpy(name1, name);
strcat(name1, "1.out");
out_file1 = fopen(name1, "w");
if(out_file1 == NULL){
fprintf(stderr, "Cannot open %s\n", name);
exit(8);
}
strcpy(name2, name);
strcat(name2, "2.out");
out_file2 = fopen(name2, "w");
if(out_file2 == NULL){
fprintf(stderr, "Cannot open %s\n", name);
exit(8);
}
while(1){
ch = fgetc(in_file);
if(ch == EOF) break;
if(ch == ' ') continue;
if((ch - '0') % 3 == 0){
fputc(ch, out_file1);
fputc(' ', out_file1);
} else {
fputc(ch, out_file2);
fputc(' ', out_file2);
}
}
fputc('\n', out_file1);
fputc('\n', out_file2);
return (0);
}
入出力結果(Terminal)
$ cc -g -o sample sample.c $ ./sample 数値リストが記述されているファイル名を入力: tmp.txt $ cat tmp.txt1.out 0 3 6 9 $ cat tmp.txt2.out 1 2 4 5 7 8 $
メモ: 二桁以上の数値のリストの場合はどうすればいいのか分からず。。
0 コメント:
コメントを投稿