|
 |
栏目导栏 |
|
| |
|
|
|
|
 |
资料搜索 |
|
| |
|
|
|
|
 |
热门文章 |
|
| |
|
|
|
|
 |
最新文章 |
|
| |
|
|
|
| |
| |
|
|
|
|
[ 作者: 加入时间:2006-08-27 09:41:41 来自:Linux联盟收集
] | |
|
打开文件的常用方法是:cKKLinux联盟 open(FH, "< $filename")cKKLinux联盟 cKKLinux联盟 or die "Couldn't open $filename for reading: $!";cKKLinux联盟 cKKLinux联盟 open() 函数通常带有两个参数,第一个为文件句柄,用于指向打开的文件, 第二个参数是文件名及模式(文件的打开模式)的混合体,如果文件被成功打开, open()函数返回true,否则为false。我们用“or”来测试该条件。cKKLinux联盟 cKKLinux联盟 上述代码中的模式由小于字符(<)来表示。如果文件不存在,open()将返回false。 此时,你可以读文件句柄,但不可以写。cKKLinux联盟 cKKLinux联盟 大于字符表示写。如果文件不存在,就会被创建。如果文件存在,文件被清除, 以前的数据将会丢失。你可以写入文件句柄,但不可以读入。cKKLinux联盟 cKKLinux联盟 # 如果文件不存在,就创建它cKKLinux联盟 cKKLinux联盟 open(FH, "> $filename")cKKLinux联盟 cKKLinux联盟 or die "Couldn't open $filename for writing: $!";cKKLinux联盟 cKKLinux联盟 如果文件不存在,添加模式(用两个大于符号表示)可以用来创建新文件,如果文 件存在,该模式并不会清除原来的数据。cKKLinux联盟 cKKLinux联盟 同“<”或“读”模式一样,你只能对文件句柄进行写操作。 (所以的写入内 容都添加到文件尾)。企图进行读操作,会产生运行错误。 cKKLinux联盟 cKKLinux联盟 open(FH, ">> $filename")cKKLinux联盟 cKKLinux联盟 or die "Couldn't open $filename for appending: $!";cKKLinux联盟 cKKLinux联盟 通过“+<”模式,你可以既可以读文件,又可以写文件。你可以通过tell() 函数在文件内部移动,通过seek()函数进行定位。如果文件不存在,就会被创建。 如果文件已经存在,原来的数据不会被清除。cKKLinux联盟 cKKLinux联盟 如果你打算清除原来的文件内容,或者自己调用truncate() 函数,或者使 用“+>”模式。cKKLinux联盟 cKKLinux联盟 open(FH, "+> $filename")cKKLinux联盟 cKKLinux联盟 or die "Couldn't open $filename for reading and writing: $!";cKKLinux联盟 cKKLinux联盟 注意“+<”和“+>”的区别,两者都可以可读可写。前者为非破坏性写, 后者为破坏性写。cKKLinux联盟 cKKLinux联盟 错误cKKLinux联盟 cKKLinux联盟 错误是如何出现的?很多地方都会出现错误:如目录不存在,文件不可写入, 你的程序丢失了文件句柄等等。cKKLinux联盟 cKKLinux联盟 你应该检查系统调用的结果 (如open() 和sysopen()),看看是否调用成功。cKKLinux联盟 cKKLinux联盟 为了帮助用户查错,通常使用“or die()”,你应记住这些用法。首先, 应写出系统调用失败(“open”)的信息。其次,应写出文件名的信息,以便修正错 误时更容易地定位。第三,要写出打开文件的方式, (“for writing,”“for appending”)。 第四,输出操作系统的出错信息(包含在$!中)。这样,一旦出现文件不能打开的问题, 使用你的程序的用户会大体上知道为什么不能打开。有时,我们把第一个和第三个合并 在一起:cKKLinux联盟 cKKLinux联盟 or die "unable to append to $filename: $!";cKKLinux联盟 cKKLinux联盟 如果在open() 和出错信息中都写了文件的全名,你会冒改变了open() 的风险, 使得出错信息不合时宜或不正确。cKKLinux联盟 cKKLinux联盟 # 下面会出现虚假的出错信息cKKLinux联盟 cKKLinux联盟 open(FH, "cKKLinux联盟 cKKLinux联盟 or die "Can't open /var/log/file.pod for writing : $!";
Linux联盟收集整理 ,转贴请标明原始链接,如有任何疑问欢迎来本站Linux论坛讨论 |
|
|
|
|
|