スライド 1

高度プログラミング演習
(11)
演習問題
• 品物名、値段をメンバーにしたデータ構造体
を作り、入出力するプログラムを作成せよ。
• 品目として、
– 食品:0
– 衣料:1
– その他:2
– と定義して、メンバーに品目を追加せよ。
• 品目の種類ごとにメンバー情報を出力するプ
ログラムを作成せよ。
演習問題
• 曲名、時間をメンバにした構造体を作り、ある音楽
CDの曲情報を入力、出力できるプログラムを作成
せよ。
• そのCDの総時間出力するプログラムを作成せよ。
• メンバに自分の注釈情報を加えるように改良せよ。
• キーワードを与え、それが注釈情報にマッチした曲
名、曲番号を出力するプログラムを作成せよ。
– > kokka
– > 3. Kimigayo
ファイル処理
• 今までは
– 入力:キーボード
• 実行のたびに入力するのでたくさん入力できない。
– 出力:画面
• 画面に表示される量は限界がある。
• ファイルを使う
– 入力:他の使いやすいエディタであらかじめファイ
ルの作成が可能。
– ファイルに書き出せばあとでゆっくり見られる。
ファイルとは?
ファイル
HDD 40GB
CPU
Pentium4 3GHz
000000: 123
000001:2345
メモリ
Main Memory 512MB
ディスク
ファイル操作
• ファイルを開ける
– open
• ファイルからデータを読み出す
– read
• ファイルにデータを書き込む
– write
• ファイルを閉じる
– close
ファイルを開く
#include <stdio.h>
#include <io.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
void main()
{
int fd,re;
char fname[128];
char ch; // int i;
while(1){
re=read(fd,&ch,1);
if(re==0)
break;
printf("%c",ch);
}
printf("Input Filename: ");
gets(fname);
fd=open(fname,O_RDONLY);
if(fd== -1){
printf("%s No such file\n");
return;
}
close(fd);
}
ファイルからデータを読み出す
#include <stdio.h>
#include <io.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
void main()
{
int fd,re;
char fname[128];
char ch; // int i;
while(1){
re=read(fd,&ch,1);
if(re==0)
break;
printf("%c",ch);
}
printf("Input Filename: ");
gets(fname);
fd=open(fname,O_RDONLY);
if(fd== -1){
printf("%s No such file\n");
return;
}
close(fd);
}
ファイルにデータを書き込む
#include <stdio.h>
#include <io.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
void main() {
int fd,re;
char fname[128];
char ch;
printf("Input Filename: ");
gets(fname);
fd=open(fname,O_WRONLY);
if(fd== -1){
printf("%s No such file\n");
return;
}
while(1){
ch=getchar();
if(ch==EOF)
break;
re=write(fd,&ch,1);
}
close(fd);
}
ファイルを閉じる
#include <stdio.h>
#include <io.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
void main() {
int fd,re;
char fname[128];
char ch;
printf("Input Filename: ");
gets(fname);
fd=open(fname,O_WRONLY);
if(fd== -1){
printf("%s No such file\n");
return;
}
while(1){
ch=getchar();
if(ch==EOF)
break;
re=write(fd,&ch,1);
}
close(fd);
}
例題問題
• ファイ名を入力して、そのファイルからデータ
を読み出すプログラムを作成せよ。
• ファイル名を入力して、そのファイルにデータ
を書き込むプログラムを作成せよ。
演習問題
• 電話番号、氏名の入ったファイルからそれら
のデータを読み込んで、指定した電話番号の
氏名を表示するプログラムを作成せよ。
演習問題
• 電話番号、氏名の入ったファイルからそれら
のデータを読み込んで、指定した電話番号ま
た氏名の情報を表示するプログラムを作成せ
よ。ユーザインタフェース仕様は自分で設計
すること。