Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quickest Way to Read First Line from File

Tags:

file

php

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.

Preferably a one-liner.

like image 805
Jonah Avatar asked Dec 23 '10 19:12

Jonah


People also ask

How do I show the first line of a text file?

The head command is used to display the beginning of a text file or piped data. By default, it displays the first ten lines of the specified files. The tail command is also used to display the ending part of the file.

What is the method to read a single line at a time from the file?

The readline() method helps to read just one line at a time, and it returns the first line from the file given. We will make use of readline() to read all the lines from the file given. To read all the lines from a given file, you can make use of Python readlines() function.


2 Answers

Well, you could do:

$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

Edit

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

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

The reason is that PHP implements RAII for resources.

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.

like image 140
ircmaxell Avatar answered Oct 06 '22 22:10

ircmaxell


$firstline=`head -n1 filename.txt`; 
like image 42
profitphp Avatar answered Oct 06 '22 20:10

profitphp