Linux文件操作---1.文件的打开及创建

头文件:

       #include <sys/types.h>
       #include <sys/stat.h>
       #include <fcntl.h>

open函数

 - int open(const char *pathname, int flags);
 - int open(const char *pathname, int flags, mode_t mode);

pathname:要打开的文件名(含路径,缺省为当前路径)

flags:
         O_RDONLY         只读打开
         O_WRONLY        只写打开
         O_RDWR            可读可写打开
         O_CREAT           若文件不存在则创建它(需说明第三个参数mode)
         O_EXCL              和O_CREAT 同时使用,而文件已存在则出错
         O_APPEND         每次写时都加到文件的尾端
         O_TRUNC           属性去打开文件时,如果文件本来有内容,而且为只读或只写成功打开,则将其长度截短为0
mode:一定是在flags中使用了O_CREAT标志,mode记录待创建的文件的访问权限。

open会返回文件描述符,当打开多个文件时,可以通过文件描述符对不同的文件进行区分。(文件打开失败返回-1)

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>

int main()
{
        int fd;

        fd = open("./file",O_RDWR);

        if(fd == -1){
                printf("open file failed\n");
                fd = open("./file",O_RDWR|O_CREAT,0600); //6=4+2
                if(fd > 0)
                {
                        printf("open file success\n");
                }
        }

        return 0;
}

权限:
1.可读          r            4
2.可写         w           2
3.执行         x            1

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值