Write to a file until it reaches a certain size

血红的双手。 提交于 2021-02-10 05:27:34

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!