如何只读取文本文件的一部分? [英] How can I read only parts of text file?

查看:173
本文介绍了如何只读取文本文件的一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PHP脚本,可以处理大型文本文件(主要是日志文件).问题是,大多数时候我只想要一部分,从一个分割点到另一个.但是,仅读取2GB文本文件就只能获取其中一小部分,这会减慢该过程的速度.

I have a PHP script that works a lot with large text files, mostly log files. The problem is that most of the time I only want a section of it, from one split point to another. But having to read a 2GB text file only to get a small portion of it is slowing the process down.

有什么方法可以只读取部分文本而不必将整个文件读取到内存中吗?

Is there any way I can read only parts of the text without having to read the entire file into memory?

数据存储如下:

|18.05.2013: some log info here...
|19.05.2013: some log info here...
|20.05.2013: some log info here...
|21.05.2013: some log info here...
|22.05.2013: some log info here...
| etc...

因此,如果我只想要"19.05.2012",那么我仍然必须阅读所有其他文本.有什么办法我只能阅读那部分?

So if I wanted only "19.05.2012" I would still have to read all the other text as well. Is there any way I can read only that part?

P.S.数据库不是一种选择,将文件拆分成较小的文件也是不切实际的.

P.S. A database is not an option, splitting the files into smaller files is also impractical.

推荐答案

我认为您正在寻找但是,您将需要以Xth字符作为Yth数据的开始的方式格式化数据.实际上,如果每个日志的长度都可以相同,则这可能是一种有效的方法.否则,您仍然需要阅读每一行以进行搜索.

You will need, however, to format your data in a way that Xth-character is the beginning of the Yth-data. Practically, if every log can have the same length, this may be an efficient way. Otherwise, you will still need to read every single lines to search for it.

让我们想象一下(未经测试,但仅是为了帮助您入门):

Let's imagine (untested, but only to get you started):

function getDataFromFile($fileName, $start, $length) {
    $f_handle = fopen($filename, 'r');
    fseek($f_handle, $start);
    $str = fgets($length);
    fclose($f_handle);
    return $str;
}

然后:

$fname='myfile.txt';
$DATA_LENGTH = 50;
$wanted_data = 12;

$data = getDataFromFile($fname, $DATA_LENGTH*$wanted_data, $DATA_LENGTH);

我希望这会有所帮助.

这篇关于如何只读取文本文件的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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