I recently encountered an interesting problem, which is to modify a certain line of characters in a file. However, the file is too large and it is impossible to read it directly with file(). I use fgets to jump to the specified line, and use fwrite to modify a certain string:
$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 to start writing in the line, you can use 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:
$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 the third line is modified
$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(#);
The methods provided by SplFileObject 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.
http://www.bkjia.com/PHPjc/486465.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/486465.htmlTechArticlep Recently I encountered an interesting problem, which is to modify a certain line of characters in a file, but the file is too large , it is impossible to read directly from file(), I use fgets to jump to the specified line,...