2012年10月28日日曜日

開発環境

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

実習14-1.

コード(TextWrangler)

sample.c

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

int main(){
  FILE *in_file;
  int count;
  int ch;
  char name[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);
  }
  count = 1;
  while(1){
    ch = fgetc(in_file);
    if(ch == EOF) break;
    if(ch == '\n') ++count;
  }
  printf("行数: %d\n", count);
  return (0);
}

入出力結果(Terminal)

$ ./sample
ファイル名を入力: sample.c
行数: 26
$

0 コメント:

コメントを投稿