1.fopen:
1.1基本定义
man fopen // open a stream
FILE *fopen(const char *pathname, const char *mode);
pathname :将要打开的文件名
mode: 文件打开的权限,有以下6种
- r read only
- r+ read and write
- w 有则清空,无则创建
- w+
- a 写到文件末尾处
- a+ read在文件开头 write放在文件末尾
r和r+需要保证文件存在,否则返回空指针。w,w+,a,a+若文件不存在会自动创建
书上有此图作为参照:
1.2 fopen的上限:
终端输入ulimit -a 打印当中的open files代表程序默认打开的流上限个数 X
而一个程序运行,会打开默认打开 stdin stdout stderr 所以程序最多打开的流 =默认打开的流上限个数 X - 3
2.fclose:
man fclose //close a stream
int fclose(FILE *stream);
stream : 通过fopen得到的返回值,作为传入的参数。
因为fopen,其实是将读到的内容分配到heap上,如果没有fclose的动作,会有内存泄漏。
3.简单的Demo
#include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { FILE *fp; static int count = 0; while (1) { fp = fopen("tmp", "r"); if (fp == NULL) { perror("fopen()"); break; } else { count++; } } printf("opened [%d]", count++); fclose(fp); exit(0); }