Copy codeThe 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 );
}
Note that after fgets obtains a row, the file Pointer Points to the end of the line (that is, the beginning of the next line). Therefore, fwrite operates on the beginning of the next line after fgets, you can use the fseek function to move the file pointer from the number of characters in the row. Note that fwrite is used to replace data, rather than insert data. Therefore, the characters following the pointer are replaced one by one. As for how to insert it, I will not study it. It is difficult to estimate. For efficiency, only one temporary file can be written. I don't know if there are other better methods.
In addition, we also see how to use SPL:
Copy codeThe Code is as follows:
$ Fp = new SplFileObject ('d:/file.txt ', 'r + ');
// Go to the second row, and the seek method parameter starts counting from 0. After testing, the Pointer Points to the end of the row, so the modification is the third row.
$ Fp-> seek (1 );
// Obtain the content of the current row (the second row)
$ Line = $ fp-> current ();
// The operations on the third row are as follows:
$ Fp-> fseek (2, SEEK_CUR );
$ Fp-> fwrite ('#');
SplFileObject provides more methods than basic file operation functions, including traversing file rows using the key/value method. SPL should have been added to PHP5. There are many other useful objects. Including array, file directory operations, exception handling, and some basic types of operations. These functions are also being added one after another. You can inherit the SPL extension methods to make it easier for us to process underlying operations.