fclose
來自 cppreference.com
定義於標頭檔案 <stdio.h> |
||
int fclose( FILE* stream ); |
||
關閉給定的檔案流。所有未寫入的緩衝資料都會重新整理到作業系統。所有未讀取的緩衝資料都會被丟棄。
無論操作是否成功,該流都不再與檔案關聯,並且由 setbuf 或 setvbuf 分配的緩衝區(如果有)也會被解除關聯,如果使用了自動分配,則會被釋放。
如果在 fclose
返回後使用指標 stream 的值,則行為未定義。
目錄 |
[編輯] 引數
stream | - | 要關閉的檔案流 |
[編輯] 返回值
成功時返回 0,否則返回 EOF
[編輯] 示例
執行此程式碼
#include <stdio.h> #include <stdlib.h> int main(void) { const char* fname = "/tmp/unique_name.txt"; // or tmpnam(NULL); int is_ok = EXIT_FAILURE; FILE* fp = fopen(fname, "w+"); if (!fp) { perror("File opening failed"); return is_ok; } fputs("Hello, world!\n", fp); rewind(fp); int c; // note: int, not char, required to handle EOF while ((c = fgetc(fp)) != EOF) // standard C I/O file reading loop putchar(c); if (ferror(fp)) puts("I/O error when reading"); else if (feof(fp)) { puts("End of file is reached successfully"); is_ok = EXIT_SUCCESS; } fclose(fp); remove(fname); return is_ok; }
可能的輸出
Hello, world! End of file is reached successfully
[編輯] 參考
- C23 標準 (ISO/IEC 9899:2024)
- 7.21.5.1 The fclose function (p: TBD)
- C17 標準 (ISO/IEC 9899:2018)
- 7.21.5.1 The fclose function (p: TBD)
- C11 標準 (ISO/IEC 9899:2011)
- 7.21.5.1 The fclose function (p: 304)
- C99 標準 (ISO/IEC 9899:1999)
- 7.19.5.1 The fclose function (p: 270)
- C89/C90 標準 (ISO/IEC 9899:1990)
- 4.9.5.1 The fclose function
[編輯] 另請參閱
(C11) |
開啟檔案 (function) |
(C11) |
用不同的名稱開啟一個現有流 (function) |
C++ documentation for fclose
|