ftruncate

(PHP 4, PHP 5)

ftruncate -- 将文件截断到给定的长度

说明

bool ftruncate ( resource handle, int size )

接受文件指针 handle 作为参数,并将文件大小截取为 size。如果成功则返回 TRUE,失败则返回 FALSE

注: 文件只会在 append 模式下改变。在 write 模式下,必须加上 fseek() 操作。

注: 在 PHP 4.3.3 之前,ftruncate() 在成功时返回一个 integer 值 1,而不是 booleanTRUE

参见 fopen()fseek()


add a note add a note User Contributed Notes
latet at poczta dot onet dot pl
14-Aug-2004 02:01
I want to report:
on Apache/2.0.48 (Linux/SuSE), PHP Version 4.3.3.

It is very different in "a" and in "r" modes.

After fopen in "a" mode, I don't have to fseek before ftruncate ($fp, 0) and even between ftruncate and the following fputs (if I need to write to the begining of the file).

But if I open in "r" mode and read some bytes, and then I want to ftruncate ($fp, 0) and write again - I do need to put fseek($fp, 0); just after ftruncate ($fp, 0).

Latet
rc at opelgt dot org
12-May-2004 09:35
I was confused by the different fopen modes (r, r+, w, w+, a, a+).
I wrote

<?php
$alt
= '1234567890';
$neu = '13579';

$datei = 'test.txt';
$dh = fopen ($datei,"w");
fwrite($dh, $alt);
fclose($dh);

$dh = fopen ($datei,"a+"); // just alter the mode to test others
rewind($dh);
echo
"Inhalt<BR>\nalt: ".fread($dh, filesize($datei))."<BR>\n";
ftruncate($dh, '0');
fwrite($dh, $neu);
rewind($dh);
echo
'neu: '.fread($dh, filesize($datei));
fclose($dh);
?>

to find out what happens:

1. For me ftruncate to a size of 0 takes the pointer to position 0 successfully. Tested under UNIX with PHP 4.2.3 and under MacOSX 10.3 with PHP 4.3.4
2. Writing to a file opened with 'a' or 'a+' always begins writing at the end of the file. A rewind before doesnt help! ('a' for always append!)

macrudi
stevedegrace von yahoo point ca
16-Nov-2003 06:07
I am using PHP 4.3.2 and I can confim you do need to seek to the beginning of the file before truncating and writing. I found that failing to rewind before truncating and writing caused my output file to be uninterpretable by some applications, but by rewinding first the desired result was achieved.
jfb
05-Sep-2003 06:30
> ftruncate does not alter the position of the file pointer

Are you sure ? On linux with PHP 4.2.2  there is no problem if I don't seek to the beginning of the file before writing.
jim dot hatfield at insignia dot com
15-Jun-2001 09:58
ftruncate does not alter the position of the file pointer. If you edit a file in-place by opening for reading and writing, reading the file, truncating and writing out again, you have to seek to the beginning before writing or you get as many NULLs as there were bytes in the original file, then your new content.