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

i want to create a file of size 1MB and also i want write on it. How to give size to a file the time of creation????

open (PP, ">/home/abc/filename.txt") or die $!; print pp $string; close PP;

i have to write logs in this file.another question is-->>> is this possible to create a different-different log files for different - different dates??? if possible then please tell me how????

Replies are listed 'Best First'.
Re: how to give size to a file at the time of creation
by Random_Walk (Prior) on May 03, 2013 at 07:52 UTC

    Not sure why you would want to start off with a big file but here you go, This makes a big file full of zeros. You could also use pack to get a null and fill it with those if you prefer. Or question marks as the requirement is puzzling :)

    use strict; use warnings; my $file = "test.meg"; my $mb = 1024 * 1024; my $meg = '0' x $mb; open my $fh, '>', $file or die "yuck, $file: $!\n"; print $fh $meg; seek $fh, 0, 0; # rewind to print at start. I guess you want this print $fh "I Write\n"; close $fh;

    Cheers,
    R.

    Pereant, qui ante nos nostra dixerunt!

      If your filesystem supports sparse files, you don't need to write it all, one byte will do:

      $ rm -f xx ; perl -wE'open$a,">","xx";seek$a,1048575,0;print$a "x"' ; +ls -l xx -rw-rw-rw- 1 merijn users 1048576 May 3 09:59 xx

      Enjoy, Have FUN! H.Merijn

        I tried seek first, but I am on a work XP box and it just gave me a small file. Like you said if your OS supports...

        Cheers,
        R.

        Pereant, qui ante nos nostra dixerunt!
Re: how to give size to a file at the time of creation
by soonix (Chancellor) on May 03, 2013 at 09:31 UTC

    From the subject line and your first question, I would think you are trying to reserve space for your file, which would be an OS dependant function, and not supported on the systems I am used to use, though I have a distant memory of VSAM where you have to do so.

    However, your second question makes me think - do you want a maximum size for your file, or automatically splitting at a given size - perhaps IO::File::Cycle does what you need?

Re: how to give size to a file at the time of creation
by hdb (Monsignor) on May 03, 2013 at 06:02 UTC

    If you want to have log files for different dates, you could make the date part of the filename:

    use strict; use warnings; my @date = localtime(time); my $filename = sprintf( "/home/abc/filename_%d_%02d_%02d.txt", $date[5 +]+1900, $date[4]+1, $date[3] ); print "$filename\n";