例子
/**
*
* Read a line number from a file
*
* @param string $file The path to the file
* @param int $line_num The line number to read
* @param string $delimiter The character that delimits lines
* @return string The line that is read
*
*/
function readLine($file, $line_num, $delimiter=" ")
{
/*** set the counter to one ***/
$i = 1;
/*** open the file for reading ***/
$fp = fopen( $file, 'r' );
/*** loop over the file pointer ***/
while ( !feof ( $fp) )
{
/*** read the line into a buffer ***/
$buffer = stream_get_line( $fp, 1024, $delimiter );
/*** if we are at the right line number ***/
if( $i == $line_num )
{
/*** return the line that is currently in the buffer ***/
return $buffer;
}
/*** increment the line counter ***/
$i++;
/*** clear the buffer ***/
$buffer = '';
}
return false;
}
?>
Example Usage
/*** make sure the file exists ***/
$file = 'my_file.txt';
if( file_exists( $file ) && is_readable( $file ) )
{
echo readLine($file, 6);
}
else
{
echo "Cannot read from $file";
}
?>
This method of iterating over the file and seeking to the line number works well and is memory efficient, but it would be nice to have PHP do the work for us. PHP provides the SPL File Object which will do exactly what is required.
/*** the file to read ***/
$file = 'foo.txt';
/**
*
* Read a line number from a file
*
* @param string $file The path to the file
* @param int $line_num The line number to read
* @return string The line that is read
*
*/
function readLine( $file, $line_number )
{
/*** read the file into the iterator ***/
$file_obj = new SplFileObject( $file );
/*** seek to the line number ***/
$file_obj->seek( $line_number );
/*** return the current line ***/
return $file_obj->current();
}
echo readLine( $file, 345678 );
?>

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

Dreamweaver Mac版
视觉化网页开发工具