从文件读取第一行的最快方法 [英] Quickest Way to Read First Line from File

查看:81
本文介绍了从文件读取第一行的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅从文件中读取第一行的最快,最简单的方法是什么?我知道您可以使用file,但就我而言,浪费时间加载整个文件毫无意义.

What's the quickest, easiest way to read the first line only from a file? I know you can use file, but in my case there's no point in wasting the time loading the whole file.

最好是单线的.

推荐答案

好吧,你可以这样做:

$f = fopen($file, 'r');
$line = fgets($f);
fclose($f);

这不是一行,但是如果您将其设置为一行,则可能会被错误地检查错误,或者使资源的开放时间超出了您的需要,所以我会说保持多行

It's not one line, but if you made it one line you'd either be screwed for error checking, or be leaving resources open longer than you need them, so I'd say keep the multiple lines

如果您绝对知道文件存在,则可以使用单线:

If you ABSOLUTELY know the file exists, you can use a one-liner:

$line = fgets(fopen($file, 'r'));

原因是PHP为资源实现了 RAII .

The reason is that PHP implements RAII for resources.

这意味着当文件句柄超出范围时(在这种情况下,在调用fgets之后立即发生),它将关闭.

That means that when the file handle goes out of scope (which happens immediately after the call to fgets in this case), it will be closed.

这篇关于从文件读取第一行的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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