Standard Input/Output and Redirection
(標準入出力とリダイレクト)
Computing Practice I
4th lecture, May 11, 2017
http://www.sw.it.aoyama.ac.jp/2017/CP1/lecture4.html
Martin J. Dürst
Today's Schedule
  - Minitest
- About last week's exercises 
    
      - Rolling pin programming
- The DRY principle
 
- String representation
- Functions for input and output
- Buffer overflow
- Standard input/output
- Why tests?
- About today's exercises
 
ミニテスト
  - 授業開始までにログイン済み
- ナビゲーションは左に畳み、ブラウザは全画面に拡大
- 授業開始まで教科書、資料、筆箱、財布などを鞄に入れ、鞄を椅子の下に
- テスト終了後その場で待つ
 
The First Book about C
  - The C Programming Language, Brian W. Kernighan and Dennis M.
    Ritchie, 1978
- In short: K&R
- Very famous, compact, concentrating on concepts
- Used Unix tools written in C for typesetting
- Origin of "hello world"example program
- Translated into many different languages (incl. Spanish and Japanese)
 
- Recommended reading for summer vacations
 
前回の演習結果
  
  
  
  
  
  
  
    
      |  | 03B1 | 03C1 | 03C2 | 03C3 | 03C4 | 
    
      | 100 points | 93 | 64 | 45 | 34 | 28 | 
    
      | 60 points | 5 | 33 | 48 | 59 | 61 | 
    
      | partial | - | - | - | - | 7 | 
    
      | error | - | 1 | 3 | 1 | - | 
    
      | not submitted | 1 | 1 | 3 | 5 | 3 | 
  
 
About Previous Exercises
  - Never forget initialization !!
- If you don't know the data used for checking in the Program Checking
    System, ask on the Q&A Forum
- Q&A Forum subjects 
    
      - Bad examples:
        「課題の提出」、「チェッキングシステムのエラー」
- Good examples: 「03C3 の check number 15 の入力」
 
- One question, one answer (the Q&A Forum is not LINE)
- If you have a problem, try to step back for a moment
 
Exercise 03C1
(Analysis of Student Numbers)
  Length of Solutions
  
  
  
  
    
      | 
 | Lines | Bytes | 
    
      | Longest | 171 | 5782 | 
    
      | Shortest | 35 | 954 | 
  
 
Rolling Pin Program
  - A program that gets longer and longer due to copy/paste
- Similar to rolling out dough with a rolling pin
- Not (yet?) a widely known term
Problems:
  - Difficult to get overview
- Difficult to check/verify
- Difficult to change
- Inefficient
- Bad feeling, (bad) code smell
 
DRY
 
The DRY Principle
  - Don't Repeat Yourself
- Don't repeat the same thing again!
- Important rule for good programs and good programmers
- Important rule for Information Technology
- Mathematical concepts: independence, orthogonality, Cartesian product,
    abstraction
- Programming concepts: repetition, function
 
Example of Cartesian Product
  
    
      | 
 | 数物理 | 化学 | 電気 | 機械 | 経シス | 情テク | ... | 
    
      | 19xx | 
 | 
 | 
 | 
 | 
 | 
 | 
 | 
    
      | 200x | 
 | 
 | 
 | 
 | 
 | 
 | 
 | 
    
      | 20xx | 
 | 
 | 
 | 
 | 
 | 
 | 
 | 
  
  - Number of individual
    combinations: 27
- Number of items when
    treating departments and year ranges independently: 11 (no need to
    distinguish 200x and 20xx)
- Independent items are easier to change when needed
 
Representation of Strings
  - In C、a string is a byte array (array of char)
- The type charcan be interpreted both as a character and as
    a small number
- The end of a string is signaled by a '\0'(null
  character)
- Example:
 char str[] = "Aoyama\n";
 
      
      
      
      
      
      
      
      
      
      
        
          | 
 | str[0] | str[1] | str[2] | str[3] | str[4] | str[5] | str[6] | str[7] |  
          | Character | 'A' | 'o' | 'y' | 'a' | 'm' | 'a' | '\n' | '\0' |  
          | Number (decimal) | 65 | 111 | 121 | 97 | 109 | 97 | 10 | 0 |  
          | Number (hexadecimal) | 0x41 | 0x6F | 0x79 | 0x61 | 0x6D | 0x61 | 0x0A | 0x00 |  
 
 
Representation of Line Breaks
  - Windows, Internet (e.g. SMTP, HTTP):
 Carriage Return, Line Feed (CRLF, 0x0D 0x0A)
- Unix/Linux/cygwin, Mac (OS 10), inside C program:
 Line Feed (LF, 0x0A)
- Old Mac (OS 9 and before):
 Carriage Return (CR, 0x0D)
- Web (e.g. HTML):
 all three possible
C on Windows: automatic conversion between CRLF (in file) and LF (in
program) 
 
Main Input/Output Functions
  
    
      | 
 | Input | Output | 
    
      | One character | getchar() | putchar(char c) | 
    
      | One line | gets(char* buffer)fgets(char*, int, stdin) | puts(char* string) | 
    
      | Formatted | scanf(char* format,...)()%s | printf(char* format,...) | 
  
 
How to Study Functions
  - Priority 
    
      - Availability of function
- Overall functionality/purpose
- Name
- Detailled specification (including return value)
 
- Where/how to get the information 
    
      - mancommand
- Manuals/books
- World Wide Web
 
 
Return Values of Input/Output Functions
  - getchar: Character (number) or- EOF(end of
  file)
- putchar: Character output or- EOFin case of
    errors
- fgets: Buffer (address) or- NULLif nothing was
    read
- puts: A non-negative integer or- EOF
- scanf: Number of successfully read variables or- EOF
- printf: Number of characters output
 
入力の定石
  - プログラムにはよく出てくるパターン (定石)
  が存在
- これはプログラム言語の「言い回し」(idiom, pattern)
- 文法の勉強だけではなく、定石の勉強も大事
- ただ使うだけではなく、理解するのが大事
Example:
while ((c = getchar()) != EOF) { ... }
(Attention: c has to be of type int, not
char)
 
Buffer Overflow
C 言語のメモリの扱い:
  - あるプログラムに与えられたメモリは勝手に使ってよい
    (プログラマの責任)
- 他のプログラムが使用するメモリは使用不可能
    (Segmentation Faultなどのエラー)
 例:int array[10]; array[20] =
  100;
- プログラム内はプログラマの責任で対応可能
- 入力 (特に一行入力) の場合は予想が不可能
- 不注意は多くのバグ (bug) と脆弱性 (vulnerability)
  の原因
 
gets の問題点
  - 多くの教科書・参考書ではまだ使用中
- 入力の長さは予想不可能
- バッファの長さが足りないと他の変数などが勝手に書き換えられる
- 本実習で禁止
- C99
    の標準で非推奨、C11
    で標準から除去
(演習問題 04B1 参照)
 
scanf の要点
例: scanf ("%lf", &doubleVar);
printf と少々書き方が違う
%s は gets
と同様に大問題 (演習問題 04B1 参照)
 
標準入出力
  - 入力一つ、出力一つのプログラムが非常に多い
- これらは「標準入力」(standard input, stdin)
    と「標準出力」(standard output,stdout)
  と呼ばれる
- C のプログラムではこれらは常に準備されている
- 標準入力はどこから、標準出力はどこへかはプログラムではなく、環境で決定
- 環境は普通標準入力がキーボードから、標準出力は画面へと設定
- ファイルとデバイス (キーボード、画面)
    を同等に扱う考え方は Unix で生まれた
 
リダイレクトとパイプ
  - リダイレクト (redirect)
    によって、標準入出力の「交通整理」が可能
- 入力のリダイレクト (ファイルからの入力)
 例:$ ./prog1 <inputfile.txt
- 出力のリダイレクト (ファイルへの出力)
 例:$ ./prog1 >outputfile.txt
- 入力と出力のリダイレクトの組み合わせ
 例:$ ./prog1 <inputfile.txt >outputfile.txt
- あるプログラムの出力と次のプログラムの入力の接続
    (パイプ、pipe)
 例:$ prog1 | prog2
 
標準入出力の応用
  - キーボード入力の手間の省略
- 出力の保存、分析
- ファイルの簡単な処理
- 複数の簡単なプログラムの組み合わせによる強力な処理
- プログラムのテスト
 
標準入出力によるプログラムのテスト
  - 入力の例のファイル (例えば 04A1in.txt)
    を用意
- 期待される出力のファイル (04A1check.txt)
    を用意
- プログラムをリダイレクトで実行、出力を別のファイル
    (04A1out.txt) に保存
 $ gcc 04A1.c && ./a <04A1in.txt
    >04A1out.txt
- 実際の出力と期待された出力を比較 (diffコマンドで)
 $ diff 04A1out.txt 04A1check.txt
 (出力が二つのファイルの差分なので、出力がなかったら成功)
- コンパイル・実行・比較を一行で総括
 $ gcc 04A1.c && ./a <04A1in.txt |
    diff - 04A1check.txt
 (出力がない場合、テストが成功)
 
Why Tests?
  - Smoth development with small steps
- Base for talking with customer
- First step towards a specification document
- Early detection of bugs
- Best for regression tests
 (check that a change in one part of a program doesn't produce bugs in other
    parts of the program)
- Very important in practice
 
今週の演習問題
04A1: 一文字の入力と出力 ('\'' は \
の文字列ではなく、' 一文字 (\
でエスケープ))
04A2: 文字の番号の調査
04A3: 大文字と小文字の入れ替え
04B1: バグの入ったプログラムの分析と修正
(今日必ず先生に提出)
04B2: 様々な型の入出力 (教科書 pp. 385-387 参照)
04C1 (部分点): ヒント:
入力の一文字ずつ枝分かれを使うか、小さいバッファーに一文字ずらしながら読み込むなど
挑戦 (部分点、最低10点)
は必須、完成は発展問題、月曜日締切
 
次回の準備
  - 宿題として残りの演習課題の完成・提出
- 今日の復習
- 教科書の第 8 章 (関数、pp. 179-203) と第 9 章 (復習:
    配列) を読む
 
Glossary
  - typesetting
- 組版
- rolling pin
- 麺棒
- principle
- 原則
- independence
- 独立性
- orthogonality
- 直交性
- Cartesian product
- 直積
- abstraction
- 抽象化
- repetition
- 繰り返し
- function
- 関数
- specification
- 仕様
- return value
- 戻り値
- input
- 入力
- output
- 出力
- string
- 文字列
- byte array
- バイトの配列
- interpret
- 解釈する
- null character
- ナル文字
- input
- 入力
- output
- 出力
- buffer overflow
- バッファ・オーバーフロー
- standard input/output
- 標準入出力
- specification (document)
- 仕様 (書)
- bug
- バグ
- regression test
- 退行テスト、回帰テスト、再帰テスト