免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 4565 | 回复: 6
打印 上一主题 下一主题

求教:如何打开一个文件,既可以读,又可以追加写 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-06-19 11:17 |只看该作者 |倒序浏览
我发现如果一个文件如下打开:
open FILE, ">>", "file_name"

只可以追加写,不可以读?

如果要读,还需要再重新打开:
open FILE, "<", "file_name"

能不能同时读和追加写?谢谢!

论坛徽章:
1
2015年辞旧岁徽章
日期:2015-03-03 16:54:15
2 [报告]
发表于 2008-06-19 11:19 |只看该作者
perldoc perlopentut
我不知道你是从哪里学到 open 这个函数的,
不过我觉得只要你找到当初你学 open 的那个地方,肯定会有说明的。

论坛徽章:
0
3 [报告]
发表于 2008-06-19 11:43 |只看该作者

回复 #2 flw 的帖子

谢谢flw,
我看的是小骆驼书,第4版。刚学perl


我有点糊涂了, 看看下面这两段代码有何不同?

(1)
open FD, ">>", "file_name";

while (<FD>) {
    if (/hello/i) {
        print "match hello\n";
    }
}

(2)
@ARGV = wq/file_name/;

while(<>) {
    if (/hello/i) {
        print "match hello\n";
    }
}


为什么这两段的代码行为不同? 前者不能读和匹配,后者可以读和匹配。

[ 本帖最后由 afeiguo 于 2008-6-19 15:06 编辑 ]

论坛徽章:
0
4 [报告]
发表于 2008-06-19 15:20 |只看该作者

回复 #3 afeiguo 的帖子

读的文件名指定不一样,肯定不同撒。。。你先了解什么是“@ARGV = wq/file_name/;”先

论坛徽章:
0
5 [报告]
发表于 2008-06-19 16:26 |只看该作者

回复 #4 不死草 的帖子

可能楼上的误解了我的意思,重新叙述一遍:
我当前目录有关文件,文件名为"test"
下面这两段代码行为不同:
(1)
open FD, ">>", "test";

while (<FD>) {
    if (/hello/i) {
        print "match hello\n";
    }
}

(2)
@ARGV = wq/test/;

while(<>) {
    if (/hello/i) {
        print "match hello\n";
    }
}

但是,稍微改动一下,下面这两段代码的行为就相同了:
(1)
open FD, "<", "test";

while (<FD>) {
    if (/hello/i) {
        print "match hello\n";
    }
}

(2)
@ARGV = wq/test/;

while(<>) {
    if (/hello/i) {
        print "match hello\n";
    }
}

所以, 我想弄清楚的是:
为什么用open FD, ">>", "test"; 打开的文件句柄没有读的功能呢?
    还是我的用法不正确?

论坛徽章:
0
6 [报告]
发表于 2008-06-19 17:40 |只看该作者

回复 #1 afeiguo 的帖子

open FILEHANDLE, MODE, EXPR
The available modes are the following:
mode        operand        create        truncate
read        <               
write        >        ✓        ✓
append        >>        ✓       

Each of the above modes can also be prefixed with the + character to allow for simultaneous reading and writing.
mode            operand              create        truncate
read/write                +<               
read/write                +>                        ✓        ✓
read/append    +>>                        ✓


With "+>>"  is READING and APPENDING mode But you must RESET the pointer position with seek()!
For example:
open F, '+>>', 'file.txt';
seek F, 0, 0;
while (<F>) {print $_;}
print F 'something new', "\n";
close F

论坛徽章:
0
7 [报告]
发表于 2008-06-19 19:51 |只看该作者
谢谢umler,解释的相当清楚。

也就是说,如果用"+>>"打开进行文件读的时候,由于读写文件指针指向文件尾(这是由于append的缘故),所以读出的肯定是eof。
如果想读取,首先得要seek到文件开始;
接着要追加的话,首先也得要seek到文件尾。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP