问题
I am writing an XML file for sitemap and Google says that the file cannot be greater than 10MB.
I was wondering if there is a way to write to a file until a certain file size is met, then close it and open a new one.
I have it so that once it reaches a certain number of entries, it will close file and open a new one.
I was using Number::Bytes::Human to try to get the file size with no luck.
回答1:
You may use the tell
method on a file handle to establish the offset where the next data will be written. The method is provided by IO::Seekable, which is subclassed by IO::File. Since v5.14 of Perl, IO::File
is autoloaded on demand, so there is no need to explicitly use
it
Here's an example program that writes to a file until it exceeds 10MB
use strict;
use warnings 'all';
use autodie;
use feature 'say';
open my $fh, '>', '10MB.txt';
say $fh->tell;
print $fh '1234567890' while $fh->tell < 10 * 1024 * 1024;
say $fh->tell;
close $fh;
output
0
10485760
Note that you you will have to be careful to reassemble the XML data correctly after it has been transmitted, as an XML document must contain exactly one root element
来源:https://stackoverflow.com/questions/41511936/write-to-a-file-until-it-reaches-a-certain-size