LINUX :(一)文件操作:1:文件的打开及创建

#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);

文件打开函数:1: open(要打开的文件名,打开方式); 

                        2: open(要打开的文件名,打开方式,mode权限); 

 

flags:O_RDONLY         只读打开

          O_WRONLY        只写打开

          O_RDWR            可读可写打开

          O_CREAT           若文件不存在则创建它

          O_EXCL              和  O_CREAT  同时使用,而文件已存在则出错

          O_APPEND         每次写入是都加到文件尾部

          O_TRUNC            如果文件有内容,则将其内容全部删掉,从新写入

 

O_APPEND 和 O_TRUNC用法

假设有文件:file

file 中内容为:you are good

int fd;

char *buf = "hello";

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

write(fd,buf,strlen(buf));

运行结果:file 中内容为   hellore good

当以O_APPEND方式打开时,结果为:

you are good
hello

当以O_TRUNC方式打开时,结果为:hello

 

 

 

1.int open(const char *pathname, int flags);

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

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

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

mode:一定实在flags中使用了 O_CREAT,记录待创建文件的权限(0600)。

例如:下面程序中的:

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

当文件不存在打开失败时,需要创建文件,用到或运算符(' | ' )。

 

#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);
                if(fd > 0){
                        printf("open file succeess\n");
                }
        }

        close(fd);

        return 0;
}

open函数返回值为整型。

所以:int fd=open(   ,   );

当文件打开失败返回值为:-1

 

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值