(一)和菜鸟一起学unix 之文件I/O:open ,close

在unix系统中大多文件I/O只用到5个函数,open ,close,write,read lseek.

文件描述符:

对于内核而言,所有文件的打开都通过文件描述符引用。

文件描述符是一个非负整数。

当我们打开一个文件或创建一个文件时,内核像进程返回一个文件描述符。

当读写一个文件的时候,用open返回的文件描述符标识该文件,将其作为一个参数传送给read或write。

首先我们找男人(man)看下open函数 ,

man open

NAME
       open, creat - open and possibly create a file or device

名字 open, creat  可以打开和创建一个文件或管理它

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);
       int creat(const char *pathname, mode_t mode);

pathname:是要打开文件夹或创建文件夹得名字 flags:说明函数的多个选项 

O_RDONLY  以只读的方式打开文件
O_WRONLY  以只写的方式打开文件
O_RDWR    以读写方式打开文件
以上三种打开方式是互斥的。
但可以利用‘|’运算符组合
O_APPEND  每次写的时候都加到文件的末尾
O_CREAT   若文件不存在就创建它,使用此选项的时候,必须同时说明第三个参数mode
O_EXCL    如果同时制定了O_CREAT,而文件已经存在,则出错。这可以测试一个文件是否存在,若不存在则创建此文件。
O_TRUNC   如果此文件存在,而且为读写或只写成功打开,则将其长度截断为0。

返回:若成功为文件描述符,若出错返回-1

man close:


NAME
       close - close a file descriptor  //关闭一个文件描述符

SYNOPSIS
       #include <unistd.h>

       int close(int fd);

例子:

#include<stdio.h>
  #include<unistd.h>
  #include<sys/types.h>
  #include<sys/stat.h>
  #include<fcntl.h>
 
   int main(void)
   {
      int fp;
     if((fp = open("test.txt",O_RDWR|O_CREAT|O_APPEND )) < 0)
         perror("open  file fail:");
      else
         printf("file open\n");
      close(fp);

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值