[ 永遠的UNIX::UNIX技術資料的寶庫 ]   GB | BIG5

首頁 > 編程技術 > Perl > 正文
Perl的經典用法:用Sysopen()進行更多的控制
本文出自:www.zdnet.com.cn 作者:Nathan Torkington (2001-12-29 13:00:00)

為了更好的控制文件的打開方式,可以使用 sysopen() 函數:

use Fcntl;

sysopen(FH, $filename, O_RDWR|O_CREAT, 0666)

or die "Can't open $filename for reading/writing/creating : $!";

函數 sysopen() 帶有四個參數,第一個是同open()函數類似的文件句柄參數, 第二個參數是不帶模式信息的文件名,第三個參數是模式參數,由Fcntl 模塊提供 的邏輯OR運算組合起來的常數構成,第四個參數(可選),為八進制屬性值(0666表示 數據文件, 0777表示程序)。如果文件可以被打開,sysopen() 返回true,如果打開失敗, 則返回false。

不同open()函數,sysopen()不提供模式說明的簡寫方式,而是把一些常數組合起來, 而且,每個模式常數有唯一的含義,只有通過邏輯OR運算才能將它們組合起來,你可以設 置多個行為的組合。

O_RDONLYRead-only

O_WRONLY Write-only

O_RDWR Reading and writing

O_APPEND Writes go to the end of the file

O_TRUNC Truncate the file if it existed

O_CREAT Create the file if it didn't exist

O_EXCLError if the file already existed (used with O_CREAT)

當你需要小心行事的時候,就使用sysopen() 函數,例如,如果你打算添加內容到文件 中,如果文件不存在,不創建新文件,你可以這樣寫:

sysopen(LOG, "/var/log/myprog.log", O_APPEND, 0666)

or die "Can't open /var/log/myprog.log for appending: $!";


(http://www.fanqiang.com)
    進入【UNIX論壇

相關文章
Perl的經典用法:用正則表達式對文件進行操作 (2001-12-29 13:02:04)
Perl的經典用法:讀入段落 (2001-12-29 13:01:25)
Perl的經典用法:讀入多個記錄 (2001-12-29 13:00:49)
Perl的經典用法:讀入單個記錄 (2001-12-29 13:00:27)
Perl的經典用法:用Sysopen()進行更多的控制 (2001-12-29 13:00:00)
Perl的經典用法:用Open()函數打開文件 (2001-12-29 12:58:44)
 

★  樊強制作 歡迎分享  ★