Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a large file line by line?

Tags:

php

I want to read a file line by line, but without completely loading it in memory.

My file is too large to open in memory, and if try to do so I always get out of memory errors.

The file size is 1 GB.

like image 457
adnan masood Avatar asked Nov 06 '12 07:11

adnan masood


People also ask

How do I read a file line by line?

Java Read File line by line using BufferedReader We can use java.io.BufferedReader readLine() method to read file line by line to String. This method returns null when end of file is reached.

How can I read a large text file line by line using Java?

BufferedReader is used to read the file line by line. Basically, BufferedReader() is used for the processing of large files. BufferedReader is very efficient for reading. Note: Specify the size of the BufferReader or keep that size as a Default size of BufferReader.

How do I read one line of a file at a time?

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.


1 Answers

You can use the fgets() function to read the file line by line:

$handle = fopen("inputfile.txt", "r"); if ($handle) {     while (($line = fgets($handle)) !== false) {         // process the line read.     }      fclose($handle); } else {     // error opening the file. }  
like image 81
codaddict Avatar answered Sep 22 '22 19:09

codaddict