Recently, I encountered an interesting problem: modifying a certain line of characters in a file, but the file is too large. it is impossible to directly read the file (). I used fgets to jump to the specified line, I recently encountered an interesting problem using fwrite, that is, modifying a certain line of characters in a file. However, the file is too large and it is impossible to directly read the file (). I used fgets to jump to the specified line, use fwrite to modify a string:
123456789101112131415 |
$ 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:
12345678 |
$ Fp = newSplFileObject ('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 third row is changed to $ fp-> seek (1); // get the content of the current row (second row) $ line = $ fp-> current (); // The following is the action on the third row $ 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.