rewind関数は、ファイルの入力・出力位置(ファイルオフセット)をファイルの先頭にセットします。
同じような機能のfseek関数との相違は、fseek関数はファイルのどの位置にもファイルオフセットをセットできるのに対して、rewind関数はファイルの先頭にセットできるだけです。
#include <stdio.h>
void rewind(FILE *stream);
*streamはfopen関数で取得した、ファイルポインタを指定します。
戻り値はありません。
プログラム 例
#include <stdio.h>
#include <ctype.h>
#define SIZE 1024
int main(int argc, char **argv)
{
FILE *fp;
char buff[SIZE];
char *p_buff;
int return_code = 0;
if (argc == 2) {
if ((fp = fopen(*(argv + 1), 'r')) != NULL) {
/* 1回目の出力 */
printf('---------- 1回目の出力 ----------\n');
while (fgets(buff, SIZE, fp) != NULL) {
printf('%s', buff);
}
/* 2回目の出力 */
printf('\n---------- 2回目の出力 ----------\n');
/* ファイルオフセットをファイルの先頭に戻す */
rewind(fp);
while (fgets(buff, SIZE, fp) != NULL) {
/* 英小文字を英大文字に変換 */
for (p_buff = buff; *p_buff; ++p_buff) {
*p_buff = toupper(*p_buff);
}
printf('%s', buff);
}
fclose(fp);
}
else {
printf('ファイルのオープンに失敗しました\n');
return_code = 1;
}
}
else {
printf('実行時引数の数が不当です\n');
return_code = 1;
}
return return_code;
}
例の実行結果
$ ./rewind.exe temp_1.txt ---------- 1回目の出力 ---------- Hello World!!. Bye. ---------- 2回目の出力 ---------- HELLO WORLD!!. BYE. $