Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Zeroing A File

by tc1364 (Beadle)
on Mar 17, 2006 at 21:06 UTC ( #537575=perlquestion: print w/replies, xml ) Need Help??

tc1364 has asked for the wisdom of the Perl Monks concerning the following question:

Question for you please, what Perl command/syntax is used to zero out a file that contains size that is not owned by you?

Replies are listed 'Best First'.
Re: Zeroing A File
by bluto (Curate) on Mar 17, 2006 at 21:16 UTC
    What do you mean by "zero"? Truncate to zero length? Delete?

    open my $fh, ">myfile"; # will truncate by opening it for write acces +s truncate "myfile", 0; # will truncate (if it's implemented on your +system) unlink "myfile"; # will remove it
    FYI, under unix file ownership has little to do with being able to trucate or delete it. If you are root, you can do either. Otherwise, to truncate you'll need to have write access to the file. To delete it, you'll need write and execute access to the file's parent directory.
Re: Zeroing A File
by ptum (Priest) on Mar 17, 2006 at 21:09 UTC

    Update: (added a little more code)

    You might consider:

    use strict; my $file = '/tmp/this_file'; my $fh; unless (open($fh,">$file")) { die "I can't open $file for writing: $!"; } truncate $fh, 0; close($fh);

    Of course, this example is a little contrived, since if you open the file for writing like that and then close it, I think it will truncate it without needing the truncate command. But I can conceive of using that truncate() command if I had been writing to a file and then decided to start over. I must admit, I have never used it.

    Another update: Ah, as pointed out by bluto, the truncate command also can be called in the form:

    truncate $myfile, 0;

    ... which is at least somewhat more useful.

    If the file is not owned by you, then you may need to have group- or world- writable permissions set on it, depending on your operating system.

    No good deed goes unpunished. -- (attributed to) Oscar Wilde
      thank you!

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://537575]
Approved by Corion
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (5)
As of 2021-11-30 20:36 GMT
Find Nodes?
    Voting Booth?

    No recent polls found