写入文件直到达到一定大小 [英] Write to a file until it reaches a certain size

查看:44
本文介绍了写入文件直到达到一定大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为站点地图编写XML文件,Google表示该文件不能大于10MB.

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.

我正在使用 Number :: Bytes :: Human 尝试获取没有运气的文件大小.

I was using Number::Bytes::Human to try to get the file size with no luck.

推荐答案

您可以在文件句柄上使用 tell 方法来建立将要写入下一个数据的偏移量.该方法由 IO :: Seekable 提供,由 IO :: File 子类化.自Perl v5.14起, IO :: File 会按需自动加载,因此无需明确地使用

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

下面是一个示例程序,该程序写入文件直到文件大小超过10MB

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;

输出

0
10485760

请注意,传输XML数据后,您必须小心正确地重新组装XML数据,因为XML文档必须恰好包含一个根元素

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

这篇关于写入文件直到达到一定大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆