2012年7月28日土曜日

開発環境

『実践プログラミング 第3版』 (Steve Oualline (著)、 望月 康司 (監修) (翻訳)、 谷口 功 (翻訳)、 オライリー・ジャパン、1998年、ISBN978-4900900646) II部(単純なプログラミング)の14章(ファイル入出力)14.10(プログラミング実習)実習14-2を解いてみる。

実習14-2.

コード(TextWrangler)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
  FILE *in_file;
  FILE *out_file;
  char line[100];
  char ch;
  printf("コピーするファイル名を入力: ");
  fgets(line,sizeof(line),stdin);
  line[strlen(line) - 1] = '\0';
  in_file = fopen(line,"r");
  printf("コピー先のファイル名を入力: ");
  fgets(line,sizeof(line),stdin);
  line[strlen(line) - 1] = '\0';
  out_file = fopen(line,"w");
  if(in_file == NULL){
    fprintf(stderr,"Cannot open %s\n", line);
    exit(8);
  }
  while(1){
    ch = fgetc(in_file);
    if(ch == EOF){
      break;
    }
    fputc(ch,out_file);
  }
  fclose(in_file);
  fclose(out_file);
  return (0);
}

入出力結果(Terminal)

$ cc -g -o sample sample.c
$ ./sample
コピーするファイル名を入力: sample.c
コピー先のファイル名を入力: new_sample.c
$ cat new_sample.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
  FILE *in_file;
  FILE *out_file;
  char line[100];
  char ch;
  printf("コピーするファイル名を入力: ");
  fgets(line,sizeof(line),stdin);
  line[strlen(line) - 1] = '\0';
  in_file = fopen(line,"r");
  printf("コピー先のファイル名を入力: ");
  fgets(line,sizeof(line),stdin);
  line[strlen(line) - 1] = '\0';
  out_file = fopen(line,"w");
  if(in_file == NULL){
    fprintf(stderr,"Cannot open %s\n", line);
    exit(8);
  }
  while(1){
    ch = fgetc(in_file);
    if(ch == EOF){
      break;
    }
    fputc(ch,out_file);
  }
  fclose(in_file);
  fclose(out_file);
  return (0);
}
$

0 コメント:

コメントを投稿