ファイル操作関数
ファイル操作
 ファイルは、
- オープン
 以下の操作で用いるファイルポインタ(FILE *)(ストリームという)を得る
- 読み書き
 ストリーム(FILE *)に対して入出力を行なう
- クローズ
 ストリーム(FILE *)を解消する
という手順で操作する。
- ファイルポインタはファイルに関する情報を含む構造体 FILE を指す
- FILE は<stdio.h>の中で定義されている
- プログラムのスタート時点で、標準入力、標準出力、標準エラー出力は
 自動的にオープンされている
- ファイルポインタ(FILE *)(ストリーム)はそれぞれ、stdin、stdout、stderrである
- 標準ヘッダstdio.hをインクルードする
#include <stdio.h>
 
FILE *fopen(char *filename, char *mode)
モード(mode)
|  | テキスト | バイナリ | 
| 読込み | "r" | "rb" | 
| 書出し | "w" | "wb" | 
| 追加 | "a" | "ab" | 
ファイルがオープンできた場合はそのファイルへのポインタを返す
エラーが発生した場合はNULL(ゼロ)を返す
int fclose(FILE *fp)
プログラムが正常終了するとき自動的に呼び出されるが、
自分で開けたものは自分で閉じよう!
int feof(FILE *fp)
ファイルの末尾に達しているか判定し、真偽を返す
int fseek(FILE *fp, long offset, int where)
読み書き位置を、whereで示す位置からoffsetバイトだけ相対的に変更する
基点(where)
| SEEK_SET | ファイルの先頭 | 
| SEEK_CUR | 現在地 | 
| SEEK_END | ファイルの末尾 | 
long ftell(FILE *fp)
ファイルの読み書き位置を返す
int fflush(FILE *fp)
バッファに溜まっているデータを書き出す
エラー処理
void exit(int status)
プログラムの実行を終了する(この関数からは戻ってこない)
オープンされているファイルはクローズ(fclose)され、
バッファリングされた出力は掃き出(fflush)される
戻り値は呼び出したプロセスで使うことができる
ゼロは正常終了、ゼロ以外は異常終了として扱われることが多い
HEXダンプを作ってみよう
/* ファイルの中身を16進数で表示する */
#include <stdio.h>
main()
{
	char	fname[40];
	FILE	*fp;
	int	col;
	int	c;
	printf("Input Filename: ");
	scanf("%s", fname );
	fp = fopen( fname, "rb");
	col = 0;
	while( feof(fp) == 0 )
	{
		if( col == 0 )
			printf("%04x: ", ftell(fp) );
		c = fgetc(fp) & 0xFF;
		printf("%02x ", c );
		col++;
		if( col > 15 )
		{
			printf("\n");
			col = 0;
		}
	}
	printf("\n");
	fclose(fp);
}
/* end of hd1.c */
例外処理をきちんとやろう
/* ファイルの中身を16進数で表示する */
#include <stdio.h>
main()
{
	char	fname[40];
	FILE	*fp;
	int	col;
	int	c;
	printf("Input Filename: ");
	scanf("%s", fname );
	if( !(fp = fopen( fname, "rb")) )
	{
		printf("\"%s\" not found!", fname );
		exit(1);
	}
	col = 0;
	while( feof(fp) == 0 )
	{
		if( col == 0 )
			printf("%04x: ", ftell(fp) );
		c = getc(fp) & 0xFF;
		printf("%02x ", c );
		col++;
		if( col > 15 )
		{
			printf("\n");
			col = 0;
		}
	}
	printf("\n");
	fclose(fp);
}
/* end of hd2.c */
ASCII文字ならば横に表示してみよう
/* ファイルの中身を16進数で表示する */
#include <stdio.h>
#include <ctype.h>
main()
{
	char	fname[40];
	FILE	*fp;
	int	col;
	int	c;
static	char	str[17];
	printf("Input Filename: ");
	scanf("%s", fname );
	if( !(fp = fopen( fname, "rb")) )
	{
		printf("\"%s\" not found!", fname );
		exit(1);
	}
	col = 0;
	while( feof(fp) == 0 )
	{
		if( col == 0 )
			printf("%04x: ", ftell(fp) );
		c = getc(fp) & 0xFF;
		printf("%02x ", c );
		str[col] = isprint(c) ? c : '.';
		col++;
		if( col > 15 )
		{
			printf(" %s\n", str );
			col = 0;
		}
	}
	if( col > 0 )
	{
		str[col] = '\0';
		while( col++ < 16 )
			printf("   ");
		printf(" %s\n", str );
	}
	fclose(fp);
}
/* end of hd3.c */
ファイル操作の練習問題へ