下列函数可用于打开一个标准I/O流:
- FILE *fopen (const char *path, const char *mode);
-
- 成功时返回流指针;出错时返回NULL
标准I/O – fopen – mode参数
示例
- #include <stdio.h>
- int main(int argc, char *argv[])
- {
- FILE *fp;
- if ((fp = fopen(“test.txt”, “r+”)) == NULL) {
- printf(“fopen error\n”);
- return -1;
- }
- ……
- return 0;
- }
- fopen() 创建的文件访问权限是0666(rw-rw-rw-)
-
Linux系统中umask设定会影响文件的访问权限,其规则为(0666 & ~umask)
Root用户是 022 普通用户是002用户可以通过umask函数或者命令修改相关设定
如果希望umask不影响文件访问权限,该如何设定?
- extern int errno;
- void perror(const char *s);
- char *strerror(int errno);
-
-
errno 存放错误号,由系统生成
perror先输出字符串s,再输出错误号对应的错误信息
strerror根据错误号返回对应的错误信息
示例1:
- #include
-
- int main(int argc, char *argv[])
- {
- FILE *fp;
-
- if ((fp = fopen(“test.txt”, “r+”)) == NULL) {
- perror(“fopen:”);
- return -1;
- }
- ……
- fopen: No such file or directory
-
-
-
-
- //成功失败都返回的方式
- #include
-
- int main(int argc,char *argv[]){
- FILE *fp;
-
- fp = fopen("1.txt","r");
- if(fp==NULL){
- //printf("Open file Failed\n");
- perror("fopen:");
- }else{
- perror("fopen:");
- }
- }
-
- fopen: Sunccess
- fopen: No such file or directory
示例2:
- #include
- #include
- #include
- int main(int argc, char *argv[])
- {
- FILE *fp;
- if ((fp = fopen(“test.txt”, “r+”)) == NULL) {
- printf(“fopen: %s\n”, strerror(errno));
- return -1;
- }
- ……
- fopen: No such file or directory
-
示例3:
- #include
- #include
- #include
-
- int main(int argc,char *argv[]){
- FILE *fp;
- int fpret;
- fp = fopen("1.txt","r");
- if(fp==NULL){
- perror("fopen");
- printf("fopen:%s\n",strerror(errno));
- }else{
- printf("Open file success\n");
- }
- }
- int fclose(FILE *stream);
-
示例
- #include
- #include
- #include
-
- int main(int argc,char *argv[]){
- FILE *fp;
- int fpret;
- fp = fopen("1.txt","r");
- if(fp==NULL){
- //printf("Open file Failed\n");
- perror("fopen");
- printf("fopen:%s\n",strerror(errno));
-
-
- }else{
- printf("Open file success\n");
- // perror("open");
- fpret = fclose(fp);
- if(fpret==0){
- printf("file close sucess\n");
- }else{
- perror("fclose");
- }
- }
-
-
- }
注意fclose传入得* stream不能为空
程序中能够打开的文件或流的个数有限制,如何测试?
思路:循环打开流,成功则计数器累加,直到出错为止
- #include
- #include
- #include
-
- #define F_PATH "./1.txt"
-
- int main(int argc,char *argv[]){
- FILE *fp;
- int count = 0;
- while(1)
- {
- fp = fopen(F_PATH,"r");
-
- if(fp==NULL){
- printf("fopen:%s\n",strerror(errno));
- printf("count :%d\n",count);
- break;
- }
- else
- {
- //perror("fopen:");
- count ++;
- }
- }
- return 0;
- }
答案:1021 + stdin + stdout + stderr = 1024