Linux学习日记2-文件的打开与关闭

一、打开文件

在Linux系统库的定义

int open(const char *pathname,int flags);//比较常用

int open(const char *pathname,int flags,mode_tmode);

//包含的头文件:

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

返回值:

成功,返回句柄,我们后面对于文件的读写,关闭等都通过句柄来操作。

失败,返回-1

参数说明:

grep -nr "xxxx"./

pathname:文件的路径名,如果只写文件名,就默认当前目录,如果在文件名加上路径,就按照绝对路径来打开文件。

flags:表示打开文件后用的操作

底层是一个宏,它可能以十六进制的形式存放。

O_RDONLY:只读模式 0x 0000 0000

O_WRONLY:只写模式 0x 00000001

O_RDWR     :可读可写 0x 00000002

1.采用路径的形式打开文件

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

int main()
{
        int fd;//file describe

        fd = open("/home/zmk/mm",O_RDONLY);

        if(fd == -1)
        {
                printf("open failed!  \r\n");
                return -1;
        }
        printf("open successed!\r\n");
        return 0;

}
~  

2.以操作文件名打开文件   如果只写文件名,就默认当前目录

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

int main()
{
        int fd;//file describe

        fd = open("mm",O_RDONLY);

        if(fd == -1)
        {
                printf("open failed!  \r\n");
                return -1;
        }
        printf("open successed!\r\n");
        return 0;
}
~     

参数说明:

O_APPEND 表示追加,如果原来文件里面有内容,则这次写入会写在文件的最末尾0x00002000

O_CREAT    表示如果指定文件不存在,则创建这个文件 0x0000 0100

O_EXCL       表示如果要创建的文件已存在,则出错,同时返回-1,并且修改errno 的值。

O_TRUNC    表示截断,如果文件存在,并且以只写、读写方式打开,则将其长度截断为0。

O_NOCTTY  如果路径名指向终端设备,不要把这个设备用作控制终端

3.如果文件中没有该文件夹可通过O_CREAT指令创建出该文件夹

#include <stdio.h>

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


int main()
{
        int fd;
        fd = open("mm",O_RDONLY|O_CREAT);
        if(fd == -1)
        {
                printf("open failed!\r\n");
                return -1;
        }
        printf("open successed!\r\n");
        return 0;
}

二、关闭文件

在Linux系统库的定义: int close(int fd);

包含的头文件                 #include <unistd.h>

功能就是简单的关闭文件

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

int main()
{
        int fd;
        fd = open("mm",O_RDONLY|O_CREAT);
        if(fd == -1)
        {
                printf("open failed!\r\n");
                return -1;
        }
        printf("open successed!\r\n");


        close(fd);
        return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

.知.吾.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值