PHP reads and modifies a line of code in a large file

  • 2020-03-31 16:46:37
  • OfStack

 
$fp = fopen('d:/file.txt', 'r+'); 
if ($fp) { 
$i = 1; 
while (!feof($fp)) { 
//Modify the second row
if ($i == 2) { 
fseek($fp, 2, SEEK_CUR); 
fwrite($fp, '#'); 
break; 
} 
fgets($fp); 
$i++; 
} 
fclose($fp); 
} 

The important thing to note here is that after fgets gets a line, the file pointer points to the end of the line (that is, the beginning of the next line), so fwrite operates on the beginning of the next line after fgets, and you can use the fseek function to move the file pointer to start at the first character of the line. Another thing to note is that fwrite writes perform substitution, not insertion, so the characters behind the pointer are replaced one by one. I don't know how to insert it. It's going to be difficult. I may have to write to another temporary file for efficiency. I wonder if there is a better way.

In addition, we have seen a way to operate with SPL today:
 
$fp = new SplFileObject('d:/file.txt', 'r+'); 
//Go to the second line and the seek method parameter counts from 0. I tested the pointer to the end of the line, so I modified the third line
$fp->seek(1); 
//Get the contents of the current line (second line)
$line = $fp->current(); 
//Next is the action on the third row
$fp->fseek(2, SEEK_CUR); 
$fp->fwrite('#'); 

SplFileObject provides a few more methods than the basic file manipulation functions, including traversing the file lines using key/value methods. SPL should be added to PHP5, and there are many other useful objects. These include array, file directory operations, exception handling, some basic types of operations, and so on. These functions are still being added, and we can extend these methods by inheriting SPL to make it easier for us to handle the underlying operations.

Related articles: