linux文件操作篇 (二) 打开和关闭文件

2.1 打开文件和关闭文件

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
 头文件
int open(const char *pathname, int flags); 打开一个文件
int close(int fildes); 关闭一个文件












intopen(constchar*pathname, intflags);
//const char *pathname 是要打开的文件路径
//int flag 是文件打开的标志 。 标志有 主标志 和 副标志 。
//主标志是互斥的。三选一
//O_RDONLY只读方式打开
//O_RDWR读写方式打开
//O_WRONLY只写方式打开
//副标志可以多选
//O_APPEND--> 读写文件从文件末尾处追加
//O_TRUNC--> 若文件存在并可写,则用清空的方式打开文件
//O_CREAT--> 若文件不存在,则创建该文件
//O_EXCL--> ??

//如果用O_CREAT 方式创建不存在的文件,open则需要额外设置文件权限
intopen(constchar*pathname, intflags, mode_tmode);
//mode_t mode 用0755 或者其他权限写入即可 . 
//创建文件的另一个函数,用法同open
intcreat(constchar*pathname, mode_tmode);
//在使用完文件后,必须正常关闭文件!!
close(fd);

举个栗子:

/*
============================================================================
Name       : hello.c
Author     : 
Version     :
Copyright   : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
*/

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h> //open
#include <unistd.h> //close

intmain(void)
{
intfd;
constchar*file="./hello";

fd=open(file,O_RDWR);
if(fd<0)
{
puts("no such file .");
fd=open(file,O_RDWR|O_CREAT,0755);
if(fd<0)
{
puts("open file err !");
return-1;
}
}
puts("open file success .");

close(fd);
puts("close file success .");

returnEXIT_SUCCESS;
}

猜你喜欢

转载自www.cnblogs.com/kmist/p/10632297.html