open函数:打开或创建文件
系统调用open可以用来打开普通文件、块设备文件、字符设备文件、链接文件和管道文件,但只能用来创建普通文件,创建特殊文件需要使用特定的函数。
头文件:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
函数原型:
int open(const char *pathname,int flages);
int open(const char *pathname,int flages,mode_t mode);
pathname:需要打开或想要创建的含路径的文件名。
flags:文件状态标志位,表示打开文件的方式。
mode:如果文件被新创建,指定该权限为mode(八进制表示法);
返回值:
0:标准输出
1:标准输入
2:标准出错
我们得到的文件描述符都是从3开始的,文件描述符又称文件ID,每个文件的文件描述符都是唯一的。
返回值小于零时,表示创建或打开文件失败。
flages参数
flages参数可以用来说明open函数的多个选择,参数值可以分两类:一类是主标志,一类是副标志。
1)主标志是互斥的,使用了其中一种则不能再使用另外一种。
主标志如下:
O_RDONLY: | 以只读方式打开 |
---|---|
O_WRONLY: | 以只写方式打开 |
O_RDWR: | 以可读可写方式打开 |
2)副标志可同时使用多个,使用时在主标志和副标志直接加入按位与(|)运算符
副标志如下:
O_CREAT | 创建一个文件,文件存在时 ,也能成功。如果文件不存在时,才需要用到第三个参数mode,以说明新文件的存取权限 |
---|---|
O_EXCL | 如果O_CREAT也被设置,此命令会检查文件是否存在。若文件不存在,则创建该文件;若文件存在则导致打开文件出错,返回文件描述符-1 |
O_TRUNC | 打开文件(将文件里的内容清空) |
O_APPEND | 追加方式打开文件(不会把文件当中已经存在的内容删除) |
close()函数:
关闭一个文件,将文件描述符还给Linux系统。通过close函数关闭文件并释放相应的资源,防止内核为继续维护它而付出代价。
头文件
#include <unistd.h>
文件原型
int close(int fd);
参数
fd:即将要关闭的文件描述符。
返回值
0:成功 -1:失败
利用open函数实现touch命令:
程序如下:
O_CREAT:创建一个文件,文件存在时 ,也能成功
若 O_CREAT|O_EXCEL,文件存在时创建文件,返回的文件描述符为-1,创建失败
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main(int argc,char *arge[])//
{
int fd;
fd = open(arge[1],O_CREAT|O_EXCL | O_RDWR,0777);
if(fd < 0){
printf("creat file %s failure\n",arge[1]);
return -1;
}
printf("creat file %s is sucess, fd = %d\n",arge[1],fd);
close(fd);
return 0;
}
umask 掩码
open函数创建文件的权限=mode &(~umask)
O_RDWR :文件的权限为可读可写
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main(int argc,char *arge[])//传参
{
int fd;
fd = open(arge[1],O_CREAT | O_RDWR,0777);//与掩码0022异或,所以其权限为755
if(fd < 0){
printf("creat file %s failure\n",arge[1]);
return -1;
}
printf("creat file %s is sucess, fd = %d\n",arge[1],fd);
close(fd);
return 0;
}
O_APPEND:追加方式打开文件(不会把文件当中已经存在的内容删除)
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main(int argc,char *arge[])
{
int fd;
fd = open("./a.c",O_APPEND | O_RDWR);
if(fd < 0){
printf("open file %s failure\n",arge[1]);
return -1;
}
printf("open file %s is sucess, fd = %d\n",arge[1],fd);
close(fd);
return 0;
}
O_TRUNC 打开文件(会把已经存在的内容删除)
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main(int argc,char *arge[])
{
int fd;
fd = open("./a.c",O_TRUNC | O_RDWR);
if(fd < 0){
printf("open file %s failure\n",arge[1]);
return -1;
}
printf("open file %s is sucess, fd = %d\n",arge[1],fd);
close(fd);
return 0;
}