【linux系統編程】open函數使用


open函數屬於Linux中系統IO,用於“打開”文件,代碼打開一個文件意味着獲得了這個文件的訪問句柄。

int fd = open(參數1,參數2,參數3);

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

1.句柄(file descriptor 簡稱fd)

首先每個文件都屬於自己的句柄,例如標准輸入是0,標准輸出是1,標准出錯是2。

每打開一個文件就會返回句柄來操作這個文件,一般是從3開始,然后4,5,6一直下去。

close(fd)之后句柄就返回給系統,例如打開一個文件后fd是3,close之后再打開另外一個文件也還是3,但代表的文件不一樣了。

2.使用open前需要先包含頭文件

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>

3.參數1(pathname)

即將要打開的文件路徑,例如:“a.txt”當前目錄下的a.txt文件

4.參數2(flags)

flags分為兩類:主類,副類

主類:O_RDONLY 以只讀方式打開   /   O_WRONLY 以只寫方式打開   /O_RDWR 以可讀可寫方式打開

三這是互斥的

副類:

O_CREAT 如果文件不存在則創建該文件

O_EXCL 如果使用O_CREAT選項且文件存在,則返回錯誤消息

O_NOCTTY 如果文件為終端,那么終端不可以調用open系統調用的那個進程的控制終端

O_TRUNC 如果文件已經存在澤刪除文件中原有數據

O_APPEND 以追加的方式打開

主副可以配合使用,例如:O_RDWR|O_CREAT|O_TRUNC

5.參數3(mode)

mode:如果文件被新建,指定其權限未mode

mode是八進制權限碼,0777表示文件所有者   該文件用戶組     其他用戶都有可讀可寫可執行權限

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


int main()
{
    int fd;
    
    //創建新文件    
    fd=open("myhello",O_RDWR | O_CREAT,0777);

    if(fd == -1)
    {
        perror("open file");
        exit(1);
    }
    printf("fd = %d\n",fd);

    int ret = close(fd);
    printf("ret = %d\n",ret);

    if(ret == -1)
    {
        perror("close file");
        exit(1);
    }
}

 

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


int main()
{
    int fd;
    
    //創建新文件判斷是否存在    
    fd=open("myhello",O_RDWR | O_CREAT | O_EXCL,0777);

    if(fd == -1)
    {
        perror("open file");
        exit(1);
    }
    printf("fd = %d\n",fd);

    int ret = close(fd);
    printf("ret = %d\n",ret);

    if(ret == -1)
    {
        perror("close file");
        exit(1);
    }
}

 

 


原文鏈接:https://blog.csdn.net/weixin_39296438/java/article/details/79422068

 

        

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM