PHP code to read and modify a certain line of content in a large file_PHP tutorial

WBOY
Release: 2016-07-21 15:43:35
Original
1247 people have browsed it

Copy code The code is as follows:

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

What needs to be noted here is that after fgets obtains a line, the file pointer points to the end of the line (that is, the beginning of the next line). So fwrite operates at the beginning of the next line after fgets. As for which character of the line to start writing from, you can use the fseek function to move the file pointer. Another thing to note is that fwrite here performs a replacement operation, not an insertion operation, so the characters after the pointer will be replaced one by one. As for how to insert it, I haven't studied it yet. It is estimated to be difficult. For the sake of efficiency, we may only be able to write to another temporary file. I don't know if there is any other better method.

In addition, today I also saw how to use SPL to operate:
Copy the code The code is as follows:

$fp = new SplFileObject('d:/file.txt', 'r+');
//Go to the second line. The seek method parameters start counting from 0. I tested that the pointer points to the end of the line, so I modified it. is the third line
$fp->seek(1);
//Get the current line content (second line)
$line = $fp->current();
//The following is the operation on the third line
$fp->fseek(2, SEEK_CUR);
$fp->fwrite('#');

SplFileObject The methods provided are richer than basic file operation functions, including using key/value methods to traverse file lines, etc. SPL should be added to PHP5, and there are many other useful objects. Including arrays, file directory operations, exception handling, some basic type operations, etc. These functions are still being added. These methods can be extended by inheriting SPL to make it more convenient for us to handle the underlying operations.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/320724.htmlTechArticleCopy the code as follows: $fp = fopen('d:/file.txt', 'r+'); if ($fp) { $i = 1; while (!feof($fp)) { //Modify the second row of data if ($i == 2) { fseek($fp, 2, SEEK_CUR); fwrite($ fp, '#'...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!