Overwrite Line in File with PHP

后端 未结 7 2004
天命终不由人
天命终不由人 2020-11-30 12:37

What is the best way to overwrite a specific line in a file? I basically want to search a file for the string \'@parsethis\' and overwrite the rest of that line with somethi

7条回答
  •  执笔经年
    2020-11-30 13:12

    Your main problem is the fact that the new line may not be the same length as the old line. If you need to change the length of the line, there is no way out of rewriting at least all of the file after the changed line. The easiest way is to create a new, modified file and then move it over the original. This way there is a complete file available at all times for readers. Use locking to make sure that only one script is modifying the file at once, and since you are going to replace the file, do the locking on a different file. Check out flock().

    If you are certain that the new line will be the same length as the old line, you can open the file in read/write mode (use r+ as the second argument to fopen()) and call ftell() to save the position the line starts at each time before you call fgets() to read a line. Once you find the line that you want to overwrite, you can use fseek() to go back to the beginning of the line and fwrite() the new data. One way to force the line to always be the same length is to space pad it out to the maximum possible length.

提交回复
热议问题