歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Unix知識 >> 關於Unix >> Perl的經典用法:用Sysopen()進行控制

Perl的經典用法:用Sysopen()進行控制

日期:2017/3/6 15:49:39   编辑:關於Unix
為了更好的控制文件的打開方式,可以使用 sysopen() 函數: use Fcntl; sysopen(FH, filename, O_RDWR|O_CREAT, 0666) or die "Can't open filename for reading/writing/creating : !"; 函數 sysopen() 帶有四個參數,第一個是同open()函數類似的文件句柄參
  為了更好的控制文件的打開方式,可以使用 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: $!";

Copyright © Linux教程網 All Rights Reserved