linux基礎程式設計-檔案操作open,lseek,read,write,close
linux上面對檔案的操作可以分為兩種:1.linux系統提供的api; 2.c標準的檔案操作函式。
前者依賴於linux系統,後者是標準的c檔案操作函式與作業系統無關。
檔案操作方式主要是開啟,讀寫和關閉這三種。
在linuxapi之中主要是使用open函式,write,read,close。
open有兩個原形:
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
這三個引數比較容易看出它們的含義,pathname是檔案路徑,flags開啟檔案的標誌, mode是開啟的模式,返回值應該是開啟檔案的控制代碼。
flags標誌有下面的定義:
o_rdonly 以唯讀的方式開啟檔案
o_wronly 以只寫的方式開啟檔案
o_rdwr 以讀寫的方式開啟檔案
o_creat 建立乙個檔案
o_exec 如果使用了o_creat而且檔案已經存在,就會發生乙個錯誤
o_noblock 以非阻塞的方式開啟乙個檔案
o_trunc 如果檔案已經存在,則刪除檔案的內容
o_rdonly、o_wronly、o_rdwr三個標誌只能使用任意的乙個。
如果flags中使用了o_creat標誌,則呼叫open函式的時候需要加上開啟檔案的模式,設定檔案的使用者許可權
int open(const char *pathname, int flags, mode_t mode);
下面是mode可取的一些值,下面都是八進位制的值,使用這些值的時候需要包含標頭檔案:sys/types.h,sys/stat.h
s_irwxu 00700 使用者可以讀
s_irusr 00400 使用者可以寫
s_iwusr 00200 使用者可以執行
s_ixusr 00100 使用者可以讀、寫、
s_irwxg 00070 組可以讀
s_irgrp 00040 組可以寫
s_iwgrp 00020 組可以執行
s_ixgrp 00010 組可以讀寫執行
s_irwxo 00007 其他人可以讀
s_iroth 00004 其他人可以寫
s_iwoth 00002 其他人可以執行
s_ixoth 00001 其他人可以讀、寫
s_isuid 04000 設定使用者執行id
s_isgid 02000 設定組的執行id
呵呵,這個跟chmod命令中的後面的值差不多,個人比較喜歡用數值來代替,
用八進位制資料表示為0777等,其中4:讀許可權,2:寫許可權,1:可執行許可權,0:無許可權,每一位的值可以取其中的一位或是它們的組合
從最低位開始分別對應的許可權是:其它使用者許可權,組許可權,當前使用者許可權。
open函式開啟乙個檔案,如果開啟成功則返回乙個檔案描述符,類似於檔案控制代碼吧,這個數值是大於0的,
如果開啟檔案失敗則會返回-1,這時使用strerror(errno)可以返回錯誤的描述字串,要使用這個需要包含標頭檔案errno.h
開啟檔案之後,可以使用lseek函式對檔案的讀寫指標位置定位,lseek原型如下:
off_t lseek(int fd, off_t offset, int whence);
fd是開啟的檔案描述符,offset是與參考偏移的位置,whence是檔案參考的位置,它一共有三個位置,
seek_set 檔案開始,如果使用此偏移,那麼檔案定位到offset的位置
seek_cur 檔案讀寫指標的當前位置
seek_end 檔案結尾
lseek返回值是檔案讀寫指標移動之後的位置,-1表示失敗
取得檔案當前偏移位置可以如下: f_offset = lseek(fd, 0, seek_cur);
檔案大小可以通過下面: f_len = lseek(fd, 0, seek_end);
使用lseek函式移動好讀寫指標之後,使用read,write即可往檔案裡面讀寫資料。
#include
ssize_t read(int fd, void *buf, size_t count);
ssize_t write(int fd, const void *buf, size_t count);
這兩個函式比較容易看懂的了,從開啟的檔案,讀取count個位元組的資料到buf緩衝區,或是把buf緩衝區的count個位元組寫到檔案裡面去,
如果沒有錯誤,則會返回實際讀/寫的位元組數,如果有錯誤碼,則會返回-1.
記住一種情況,返回的實際讀寫數目可能跟你要讀寫的位元組數不一致,這個是沒有錯的,返回0表示讀寫的位元組為0.
當我們對檔案操作完成之後,需要關閉開啟的檔案
int close(int fd);
返回0表示關閉成功,-1表示關閉失敗。
乙個簡單的例子:
[cpp]view plain
copy
#include
#include
#include
#include
#include
#include
///int
main(
intargc,
char
**argv)
printf("open open_file_test ok!/n"
);
fpos = lseek(fd, 0, seek_end);
if(fpos == -1)
printf("file size:%ld/n"
, fpos);
close(fd); }
io 基本操作
1 io 可以分為 位元組流 字元流 例子 位元組流 讀乙個寫乙個 得到檔案 file file new file d test.txt try out.flush in.close out.close catch filenotfoundexception e catch ioexception ...
IO的基本操作
public void readfile string fromfilename,string tofilename os.close is.close catch ioexception e catch filenotfoundexception e finally catch ioexcepti...
基本的I O操作
功能 開啟指定的檔案,以指定的許可權開啟 你使用一下函式需要包含的標頭檔案 include include include int open const char pathname,int flags int open const char pathname,int flags,mode t mod...