ftruncate fails when fopen in a mode after vagrant-vbguest installation

Asked 2 years ago, Updated 2 years ago, 169 views

I am maintaining an old PHP script, and I want to trunk the file and overwrite it as follows, but ftruncate failed after installing and restarting vagrant-vbguest.

$file="./test.txt";
$str = "Write content";
$fp = fopen($file, 'a');
block($fp,LOCK_EX);
ftruncate($fp,0);//ftruncate return value results in false
refresh($fp);
fputs($fp,$str);
block($fp,LOCK_UN);
fclose($fp);

Because ftruncate fails, it will not be overwritten and will be added to the existing content.

[Environment]
Vagrant 2.2.5
GuestOS Centos 6.9
HostOS Windows 10 PHP version 5.3.3

GuestOS once failed to shut down and subsequently vagrant up

Vagrant was unavailable to mount VirtualBox shared folders.

An error similar to the one shown in

appears.
vagrant plugin install vagrant-vbguest

After running and installing the plug-in, it appears that the operation has changed since the virtual machine was restarted.

There seems to be no problem with anything other than ftruncate at the moment, but I'm worried because I don't know why ftruncate fails.

If fopen is set to c, w, or r, ftruncate will operate normally (return true).

If you know why ftruncate fails when fopen mode is a, and if you know about virtual machine recovery, could you please advise me?

php vagrant

2022-09-30 21:43

1 Answers

For now, I will focus on the topic of PHP.

ftruncate may fail because you must be aware that the location of the file pointer is different depending on the mode when opening the file.

If you use r, w, c, c in fopen(), the pointer position moves to the beginning of the file, so if you run .

The code in the question also says rewind, but if you want to use it, you will need to do it in the following order:

rewind($fp);
ftruncate($fp,0);

However, the rewind() description includes the following caveats:

Note:
If you open a file in postscript mode ("a" or "a+"), what is the location of the pointer to the file?
Regardless, the data that is written to the file is always added.

If you intend to overwrite the program's behavior instead of adding it, I think it is wrong to open it in adding mode (a).Use a more appropriate w or c.


2022-09-30 21:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.