using seek to read and write file lines

I have a file ie:
   line1
   line2
   line3
   line4
I would like to open the file, go directly to, say, line 3 and write something different in that location without disturbing the other lines.  The lines can be the same length.  I can use the seek function to go to that line, but my book doesn't say what code I need to read or write that line.  Do I open the file before using seek?  What code do I use to read or write that line?
donb1Asked:
Who is Participating?
 
b2piConnect With a Mentor Commented:
If you just want to read a particular line, AND all the lines are the same length, it's quite easy.

use strict;

my($LineLength);
open(FH, "a.txt);
$LineLength = <FH>;
close(FH);
$LineLength = length($LineLength);

print &ReadLine(2); ## Print the third line of the file
print &ReadLine(0); ## Print the first line of the file
print &ReadLine(4); ## Print the fifth line of the file.

sub ReadLine($) {
    my($line) = shift;

    open(FH, "<a.txt");      ## May be open, but this flushes
    seek(FH, $LineLength * $line, 0); ## 0 indicates absolute                                           ## position
    $line = <FH>;
    return $line;
}


If the lines aren't the same length, or you need to write, then I believe that the whole thing get's system dependent.  On some machines, you simply can't move the write pointer of a file without affecting the files contents.

A better way of approaching this might be to convert the file into a Berkely (or what have you) database, and then operate on it there.  You can then convert it back to a text file, if you choose.

perldoc DB_File

0
 
ozoCommented:
Yes, you open the file before you seek, what would you sek on therwise otherwise?
print FILE "line3\n"; #to write
$line = <FILE>; #to read
0
 
ozoCommented:
See also "How do I randomly update a binary file?"
in
perldoc perlfaq5
0
 
b2piCommented:
That would point you to using "+<filename".  Frankly, I feel that that is so inherently dangerous that it should almost not be allowed.

As the author (probably Tom Christenson) says:

     Locking and error checking are left as an exercise for the
     reader.  Don't forget them, or you'll be quite sorry.

That would be a non-trivial exercise.

0
All Courses

From novice to tech pro — start learning today.