linux打开文件及创建

SYNOPSIS
       #include<sys/types.h>
       #include<sys/stat.h>
       #include<fcntl.h>
       int open(const char *pathname,int flags);
       int open(const char *pathname,int flags,mode_t_ mode);
       in creat(const char *pathname,mode_t mode);
DESCRIPTION
       Given a pathname for a file,open() returns a file descriptor,a small,nonnegative interger for use in subsequent system calls (read(2),write(2),lseek(2),fcntl(2),etc.). The file descriptor returned by a successful call will be the lowest-numbered file descriptor not currently open for the process   

参数说明

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

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

Flags

O_RDONLY 只读打开
O_WRDONLY 只写打开
O_RDWR 可读可写打开

当我们附带了权限后,打开的文件就只能按照这种权限来操作。
以上这三个常数中应当只指定一个。下列常数是可选择的:
O_CREAT 若文件不存在则创建它。使用此选项时,需要同时说明第三个参数mode.用其说明该文件的存取许可权限。
O_EXCL 如果同时指定了O_CREAT,而文件已经存在,则出错。
O_APPEND 每次读写时都加到文件的尾端。
O_TRUNC 属性去打开文件时,如果这个文件中本来就是有内容的,而且为只读或只写成功打开,则将其长度截短为0

Mode:一定是在flags中使用了O_CREAT 标志,mode记录待创建的文件的访问权限

$touch file1
$vi demo1.c
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
int main(){
   // file description
   int fd;
   fd= open("./file1",O_RDWR);
   printf("fd=%d\n",fd);
    return 0;

} 
$gcc demo1.c
$./a.out
$fd=3
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
int main(){
        // file description
        int fd;
        fd= open("./file1",O_RDWR);
        if(fd==-1){
                printf("open file1 fail\n");
                fd = open("./file1",O_RDWR|O_CREAT,0600);
                if(fd>0){
                        printf("create file1 success\n");
                }
        }

        return 0;

}
~                                                                                                                                                                        

解读:0 6(4+2) 0 同组 0 其他组

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值