rewind

ファイル位置表示子 (file position indicator) をそのファイルの始めに位置付けます.

#include <stdio.h>
void rewind(
    FILE *stream
);

rewind 関数は stream が指すストリームファイル位置表示子をそのファイルの始めに位置づけ,そのストリームに対応するエラー表示子 (error indicator) をクリアします.

rewind はエラー表示子もクリアすることを除けば以下の式と同じになります.

(void)fseek(stream, 0L, SEEK_SET)

引数

C言語サンプルプログラム

rewind 関数を使用してファイル位置表示子をそのファイルの始めに位置付けるサンプルプログラムを以下に示します.

/* header files */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* main */
int main(void) {
    FILE *fp;
    char *filename = "sample.txt";
    char ch;

    /* ファイルのオープン */
    if ((fp = fopen(filename, "r")) == NULL) {
        fprintf( stderr, "%sのオープンに失敗: %s\n",
                filename, strerror(errno) );
        return EXIT_FAILURE;
    }

    /* ファイルの終端まで文字を読み取り表示する */
    while (( ch = fgetc(fp)) != EOF ) {
        putchar(ch);
    }

    /* ファイルの最初に戻す */
    rewind(fp);
    putchar('\n');

    /* ファイルの終端まで文字を読み取り表示する */
    while (( ch = fgetc(fp)) != EOF ) {
        putchar(ch);
    }

    /* ファイルクローズ */
    fclose(fp);

    return EXIT_SUCCESS;
}

実行例

サンプルプログラム内で使用する sample.txt の内容は以下のように用意したとします.

I don't want to march as much as possible.
I love SNOOPY.

サンプルプログラムの実行結果は以下のようになります.

I don't want to march as much as possible.
I love SNOOPY.

I don't want to march as much as possible.
I love SNOOPY.