PHP code for reading and modifying a line of content in a large file

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.