void rewind(FILE *fp); // 等價於 fseek(fp, 0, SEEK_SET) 並清除錯誤/EOF 標誌
int fseek(FILE *fp, long offset, int origin);
// origin: SEEK_SET(0) 文件首 | SEEK_CUR(1) 當前位置 | SEEK_END(2) 文件尾
// 返回 0 成功,非 0 失敗
// 典型用法
fseek(fp, 0, SEEK_END); // 移至文件尾
long size = ftell(fp); // 獲取文件大小
fseek(fp, 100, SEEK_SET); // 移至第 100 字節
fseek(fp, -50, SEEK_CUR); // 向前 50 字節
注意:以追加模式("a"/"a+")打開時,寫入前系統強制移至文件尾,fseek/rewind 對寫入無效。
long ftell(FILE *fp); // 返回距文件首字節數,錯誤返回 -1L
int feof(FILE *fp); // 已到達 EOF 返回非 0,否則 0
// 關鍵:只有「嘗試讀取並失敗」後才置位 EOF 標誌
int ferror(FILE *fp); // 發生錯誤返回非 0,否則 0
int remove(const char *filename); // 成功 0,失敗非 0
int rename(const char *oldname, const char *newname); // 成功 0,失敗非 0
FILE* freopen(const char *filename, const char *mode, FILE *stream);
// 典型:競程/測試時重定向 stdin/stdout
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
// 之後 scanf/printf 直接操作文件
int fclose(FILE *stream); // 成功 0,失敗 -1(EOF)
// 必須調用:刷新緩衝區、釋放資源、更新文件元數據
#include
#include
int main() {
freopen("input.txt", "r", stdin);
freopen("output.txt", "w+", stdout);
int a[10];
for (int i = 0; i < 10; i++) scanf("%d", &a[i]);
for (int i = 0; i < 10; i++) printf("%d\n", a[i]);
return 0;
}
// input.txt: 1 2 -1 3 4 5 7 8 9 10
// 輸出寫入 output.txt,控制台無輸出
NULL。"rb"/"wb")避免換行符轉換差異。fseek+ftell,順序流用 feof+ferror 判斷結束。fflush 或 fclose 確保落盤。_fseeki64/_ftelli64。