使用檔案描述符

2022-05-07 16:36:09 字數 2746 閱讀 7697

開啟和關閉檔案描述符。

#include

#include

#include

#include

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

int close(int fd);

open試圖開啟引數pathname中的乙個檔案。

引數flags指定訪問該檔案的方式。

open成功後會返回乙個檔案描述符。

open失敗後會返回-1,並設定errno變數。

#include #include 

#include

#include

#include

intmain()

open試圖開啟乙個不存在的檔案,返回-1。

如果想知道更加詳細的錯誤描述,請使用errno和strerror函式

#include #include 

#include

#include

#include

#include

#include

int main()

char s = "abc.txt";

int fd = open(s, o_rdonly);

if (fd == -1)

printf("error is %s\n", strerror(errno)); 

else

printf("success fd=%d\n", fd);

return 0;

在乙個檔案描述符用完後一定要用close()函式關閉它,這樣才能保證該程序對檔案所有加的鎖全部被釋放。

讀寫檔案描述符。

ssize_t read(int fd, void *buf, size_t count);

ssize_t write(int fd, void *bug, size_t count);

read用於從檔案描述符對應的檔案讀取資料,呼叫成功返回讀出的位元組數,

引數fd必須是用open呼叫返回的有效檔案描述符。

引數buf為讀出資料的緩衝區,count指定讀出的位元組數。

成功返回讀取位元組數,如果遇到eof,返回0,出錯返回-1。

read函式例子。

int

main()

else

return0;

}

read函式例子。

int

main()

else

close(fd);

}

return0;

}

write函式例子

int

main()

else

return

0;

使用fstat獲取檔案資訊。

int fstat(int fd, struct stat *buf)

引數fd必須是用open呼叫返回的有效檔案描述符。

使用stat獲取檔案資訊。

int stat(const char *path, struct stat *buf);

引數path是路徑加檔名的字串

struct stat定義如下:

struct

stat ;

為了正確解釋檔案型別,有一套巨集能夠計算stat介面的st_mod成員。

s_isreg(m)  is it a regular file?

s_isdir(m)  directory?

s_ischr(m)  character device?

s_isblk(m)  block device?

s_isfifo(m) fifo (named pipe)?

s_islnk(m)  symbolic link? (not in posix.1-1996.)

s_issock(m) socket? (not in posix.1-1996.)

fstat函式例子。

int

main()

else

close(fd);

}return0;

}

stat函式例子。

int

main()

else

return0;

}

讀寫使用者輸入,螢幕不回顯

char *getpass( const char *prompt);

getpass用於從鍵盤讀取使用者輸入,但螢幕不回顯。

引數prompt為螢幕提示字元。

函式返回值為使用者鍵盤輸入的字串。

getpass函式例子。

int main()

char *s = getpass("please input:");

printf("%s\n", s);

return 0;

複製去google翻譯

mysql 檔案描述符 檔案描述符

toc 首先,linux的世界裡一切皆為檔案,無論是裝置還是乙個socket連線。檔案又可分為 普通檔案 目錄檔案 鏈結檔案和裝置檔案。檔案描述符 file descriptor 是核心為了高效管理已被開啟的檔案所建立的索引,其是乙個非負整數 通常是小整數 用於指代被開啟的檔案,所有執行i o操作的...

檔案描述符

檔案描述符 是個很小的正整數,它是乙個索引值,指向核心為每乙個程序所維護的該程序開啟檔案的記錄表。檔案描述符的優點 相容posix標準,許多 linux 和unix 系統呼叫都依賴於它。檔案描述符的缺點 不能移植到unix以外的系統上去,也不直觀。基於檔案描述符的輸入輸出函式 open 開啟乙個檔案...

檔案描述符

作業系統程序表中存放各個檔案進行檔案描述 核心 kernel 利用檔案描述符 file descriptor 來訪問檔案。檔案描述符是非負整數。開啟現存盤案或新建檔案時,核心會返回乙個檔案描述符。讀寫檔案也需要使用檔案描述符來指定待讀寫的檔案。目錄檔案描述符概述 如何建立檔案描述符 使用的好處 缺點...