The task: to replace three characters in a row in a file whose position starts from position N. I searched for a solution for a long time and all the time it came down to reading the file and putting it into a variable as a string. Then find the desired area or position, change the variable and overwrite the file. But if the file turns out to be 10 tons of characters and very frequent point changes occur, it turns out, as it seems to me, a large load (at least unnecessary). I tried to make another solution - using fseek () I find the right position in the open file, but I don’t know how to replace the next 3 characters. If you use fwrite (), then the characters will be added, not replaced.
1 answer
You do everything right , but the main thing is to set the correct mode when using the fopen function. Of course, the file will be added with data if you put the mode a (or a + ), which move the pointer to the end.
If you put the mode w or w + , then in fact you overwrite the entire file, because This mode cuts the file to zero length. But using the c , c + or r + mode suits us, because they work with the current file and its data, moving the pointer to the very beginning and not cutting the file.
The algorithm is simple: open the file, move the pointer to the desired number of bytes, write down the required number of characters from this position and close the pointer.
$file = fopen("text.txt", "c"); //открываем файл с режимом c fseek($file, 3); //перемещаем указатель (0 - это начало файла) fwrite($file, "www"); //пишем по указателю свои данные fclose($file); //закрываем файл
If I had a file with the contents of ' wwwttt.ru ', then after executing the script the file will contain ' wwwwww.ru ', since we shifted the pointer to 3 bytes and placed it in front of t, and then we wrote down our 3 characters, which replaced the existing ones.
By the way, if you want to write this operation in OOP style, you can use the built-in SplFileObject
$file = new SplFileObject('text.txt', 'c'); $file->fseek(3); $file->fwrite("www"); $file = null; //close file