fclose
来自 cppreference.cn
定义于头文件 <stdio.h> |
||
int fclose( FILE* stream ); |
||
关闭给定的文件流。任何未写入的缓冲数据会被刷新到操作系统。任何未读取的缓冲数据会被丢弃。
无论操作是否成功,该流不再与文件关联,并且由 setbuf 或 setvbuf 分配的缓冲区(如果有)也会被解除关联,如果使用了自动分配,则会被释放。
如果在 fclose 返回后使用指针 stream 的值,则行为是未定义的。
目录 |
[编辑] 参数
stream | - | 要关闭的文件流 |
[编辑] 返回值
0 成功时返回 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 fclose 函数 (p: TBD)
- C17 标准 (ISO/IEC 9899:2018)
- 7.21.5.1 fclose 函数 (p: TBD)
- C11 标准 (ISO/IEC 9899:2011)
- 7.21.5.1 fclose 函数 (p: 304)
- C99 标准 (ISO/IEC 9899:1999)
- 7.19.5.1 fclose 函数 (p: 270)
- C89/C90 标准 (ISO/IEC 9899:1990)
- 4.9.5.1 fclose 函数
[编辑] 参见
(C11) |
(function) 打开一个文件 |
(C11) |
(function) 用不同的名称打开现有流 |
C++ 文档 for fclose
|