基本IO函式的使用

2021-08-25 13:06:27 字數 1777 閱讀 9584

摘要:本文簡單介紹檔案操作的三個函式(open,read,write)的基本用法。

詳細說明了open函式的用法。

所需標頭檔案:

#include

#include

#include

函式定義:

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

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

函式說明:

引數 pathname 指向欲開啟的檔案路徑字串。下列是引數 flags 所能使用的旗標:

o_rdonly 以唯讀方式開啟檔案

o_wronly 以只寫方式開啟檔案

o_rdwr以可讀寫方式開啟檔案。

上述三種旗標是互斥的,也就是不可同時使用,但可與下列的旗標利用 or(|)運算子組合。

返回值:

若所有欲核查的許可權都通過了檢查則返回 0 值,表示成功,只要有 乙個許可權被禁止則返回-1。

錯誤**:

eexist 引數 pathname 所指的檔案已存在,卻使用了 o_creat和 o_excl 旗標

eaccess 引數 pathname 所指的檔案不符合所要求測試的許可權。

erofs欲測試寫入許可權的檔案存在於唯讀檔案系統內。

efault 引數 pathname 指標超出可訪問記憶體空間。

einval 引數 mode 不正確。

enametoolong 引數 pathname 太長。

enotdir 引數 pathname 不是目錄。

enomem 核心記憶體不足。

eloop 引數 pathname 有過多符號連線問題。

eio i/o 訪問錯誤。

範例:#

include

#include

#include

#include

#include

int main(

void

)write

( fd, s,

sizeof

(s))

;//向該檔案中寫入乙個字串

close

( fd )

;fd =

open

("temp.log"

, o_rdonly );if

(-1 =

= fd )

size =

read

( fd, buffer,

sizeof

(buffer));

//讀取檔案內容儲存到buffer指定的字串陣列中,返回讀取的字元個數

close

( fd )

;printf

("%s"

, buffer )

;return 0;

}

fopen()返回的是 file* 型別的, 檔案流

open()返回的是檔案描述符, int型的

fgets(char * buffer, int length, file * infile)

fputs(char * buffer, file * outfile)

read(int fd, char * buffer, int length)

write(int fd, char * buffer, int length)

file *popen(char * command, char * type)

int pipe(int fd[2]);

標準IO操作基礎函式基本使用

說明 fopen,fdopen,freopen stream open functions include file fopen const char pathname,const char mode 例子1 include include include include intmain puts ...

函式的基本使用

函式就是一種工具,事先準備工具 的過程就是函式的定義,拿來就用 就是函式的呼叫 函式可以重複呼叫 1.防止 冗餘 2.的可讀性差 定義函式 製造工具 呼叫函式 使用工具 函式的使用原則 先定義,後呼叫 函式的命名規範和變數名一樣 def index 引數1,引數2.def 關鍵字 index 函式名...

IO的基本操作

public void readfile string fromfilename,string tofilename os.close is.close catch ioexception e catch filenotfoundexception e finally catch ioexcepti...