Changing fopen () mode halfway?

I have this piece of code:

$file = fopen($path, 'r+'); flock($file, LOCK_EX); // reading the file into an array and doing some stuff to it for ($i=0; $i<count($array); $i++) { fwrite($file, $array[$i]); } flock($file, LOCK_UN); fclose($file); 

Basically what I want to do: open the file> lock it> read> do something> clear the file > write to the file> unlock it> close it.

The problem is the clearing part. I know I can do this with fopen($file, 'w+') , but then reading will be a problem. Maybe I can somehow change the mode ?

Any help would be appreciated Paul

+4
source share
3 answers

If you set the pointer to 0 using fseek , you can run ftruncate as follows:

 // reading the file into an array and doing some stuff to it //1 fseek($handle,0); //Set the pointer to the first byte //2 ftruncate($handle,filesize("yourfile.ext")); //from the first byte to the last truncate //3 - File should be empty and still in writing mode. for ($i=0; $i<count($array); $i++) { fwrite($file, $array[$i]); } 

With ftruncate remember that these problems relate to the second parameter:

+5
source
 fopen($file, 'r+') 

Includes reading and writing. Go ahead and prosper.

r + description: Open for reading and writing; place the file pointer at the beginning of the file.

w + description: Open for reading and writing; place the file pointer at the beginning of the file and trim the file to zero length. If the file does not exist, try to create it.

Source: http://php.net/manual/en/function.fopen.php

0
source

You can have a separate empty lock file and call flock ($ file, LOCK_EX); in this file and open another file for writing.

0
source

Source: https://habr.com/ru/post/1336047/


All Articles