fclose
From cppreference.net
File input/output
| Types and objects | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
定义于头文件
<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"; // 或使用 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; // 注意:需使用 int 类型而非 char 类型来处理 EOF while ((c = fgetc(fp)) != EOF) // 标准 C I/O 文件读取循环 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 fclose 函数 (页: TBD)
- C17 标准 (ISO/IEC 9899:2018):
-
- 7.21.5.1 fclose 函数 (页: TBD)
- C11 标准 (ISO/IEC 9899:2011):
-
- 7.21.5.1 fclose 函数 (页: 304)
- C99标准(ISO/IEC 9899:1999):
-
- 7.19.5.1 fclose函数(页码:270)
- C89/C90 标准 (ISO/IEC 9899:1990):
-
- 4.9.5.1 fclose 函数
参考
|
(C11)
|
打开文件
(函数) |
|
(C11)
|
使用不同名称重新打开现有流
(函数) |
|
C++ 文档
关于
fclose
|
|