fig10_09.pl

来自「PERL语言资料 可以用于PERL程序设计」· PL 代码 · 共 56 行

PL
56
字号
#!/usr/bin/perl
# Fig. 10.7: fig10_07.pl
# random access file

use strict;
use warnings;

print "Creating a file with the numbers 0-9.\n";
open FILE, "+>file.txt" or die "Unable to open file: $!\n";
print FILE "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n";
close FILE or die "Unable to open file: $!\n";

open FILE, "<file.txt" or die "Unable to open file: $!\n";
<FILE>;
my $length = tell( FILE );
close FILE or die "Unable to open file: $!\n";

open FILE, "+<file.txt" or die "Unable to open file: $!\n";
print "Going to the sixth item.\n";
seek( FILE, ( 6 - 1 ) * $length, 0 );

print "Truncating remainder of file at ", tell(FILE), " bytes.\n";
truncate(FILE, tell(FILE)) or die "Unable to truncate : $!\n";

print "Printing the third item:\n";
seek( FILE, ( 3 - 1 ) * $length, 0 );
my $in = <FILE>;
print "$in";
print "Printing the rest of the file:\n";
print while ( <FILE> );

print "Updating the second item.\n";
seek( FILE, ( 2 - 1 ) * $length, 0 );
print FILE "7";
seek( FILE, 0, 0 );
print "The file now reads:\n";
print while ( <FILE> );

close FILE or die "Unable to close file: $!";

###########################################################################
#  (C) Copyright 2001 by Deitel & Associates, Inc. and Prentice Hall.     #
#  All Rights Reserved.                                                   #
#                                                                         #
#  DISCLAIMER: The authors and publisher of this book have used their     #
#  best efforts in preparing the book. These efforts include the          #
#  development, research, and testing of the theories and programs        #
#  to determine their effectiveness. The authors and publisher make       #
#  no warranty of any kind, expressed or implied, with regard to these    #
#  programs or to the documentation contained in these books. The authors #
#  and publisher shall not be liable in any event for incidental or       #
#  consequential damages in connection with, or arising out of, the       #
#  furnishing, performance, or use of these programs.                     #
###########################################################################

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?