|
TOP
|
| Perl的经典用法:用Sysopen()进行更多的控制 |
|
为了更好的控制文件的打开方式,可以使用sysopen()函数: useFcntl; sysopen(FH,$filename,O_RDWR|O_CREAT,0666) ordie"Can'topen$filenameforreading/writing/creating:$!"; | | 函数sysopen()带有四个参数,第一个是同open()函数类似的文件句柄参数,第二个参数是不带模式信息的文件名,第三个参数是模式参数,由Fcntl模块提供的逻辑OR运算组合起来的常数构成,第四个参数(可选),为八进制属性值(0666表示数据文件,0777表示程序)。如果文件可以被打开,sysopen()返回true,如果打开失败,则返回false。 不同于open()函数,sysopen()不提供模式说明的简写方式,而是把一些常数组合起来,而且,每个模式常数有唯一的含义,只有通过逻辑OR运算才能将它们组合起来,你可以设置多个行为的组合。 O_RDONLYRead-only O_WRONLYWrite-only O_RDWRReadingandwriting O_APPENDWritesgototheendofthefile O_TRUNCTruncatethefileifitexisted O_CREATCreatethefileifitdidn'texist O_EXCLErrorifthefilealreadyexisted(usedwithO_CREAT) | | 当你需要小心行事的时候,就使用sysopen()函数,例如,如果你打算添加内容到文件中,如果文件不存在,不创建新文件,你可以这样写: sysopen(LOG,"/var/log/myprog.log",O_APPEND,0666) ordie"Can'topen/var/log/myprog.logforappending:$!"; | |