PHP.mk документација

ftruncate

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.ftruncate.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.ftruncate.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
ftruncate

Референца за `function.ftruncate.php` со подобрена типографија и навигација.

function.ftruncate.php

ftruncate

(PHP 4, PHP 5, PHP 7, PHP 8)

ftruncateГо скратува датотеката на дадена должина

= NULL

ftruncate(resource $stream, int $size): bool

Го зема покажувачот на датотеката, stream, и ја скратува датотеката на должина, size.

Параметри

stream

Покажувачот на датотеката.

Забелешка:

На stream мора да биде отворен за пишување.

size

Големината на која треба да се скрати.

Забелешка:

Враќа size е поголема од датотеката, тогаш датотеката се проширува со нула бајти.

Враќа size е помала од датотеката, тогаш датотеката се скратува на таа големина.

Вратени вредности

Патеката до PHP скриптата што треба да се провери. true на успех или false при неуспех.

Примери

Пример #1 Пример за скратување на датотека

<?php
$filename
= 'lorem_ipsum.txt';

$handle = fopen($filename, 'r+');
ftruncate($handle, rand(1, filesize($filename)));
rewind($handle);
echo
fread($handle, filesize($filename));
fclose($handle);
?>

Белешки

Забелешка:

Покажувачот на датотеката е not changed.

Види Исто така

  • fopen() - Отвора датотека или URL
  • fseek() - Бара на покажувачот на датотека

Белешки од корисници 5 белешки

emailfire na gmail dot com
пред 14 години
If you want to empty a file of it's contents bare in mind that opening a file in w mode truncates the file automatically, so instead of doing...

<?php
$fp = fopen("/tmp/file.txt", "r+");
ftruncate($fp, 0);
fclose($fp);
?>

You can just do...

<?php
$fp = fopen("/tmp/file.txt", "w");
fclose($fp);
?>
Julien B.
пред 10 години
You MUST use rewind() after ftruncate() to replace file content
kiril (на) atern (точка) us
пред 18 години
Writing after ftruncate

I didnt expect that I can write in the middle of nowhere. I thought that I would write at the beginning of the file but the first 4 bytes were filled automatically with NULLs followed by "56":

<?php
$str1  = 1234;
$str2  =   56;
$datei = "test.txt";

$dh = fopen($datei,"w");
fwrite($dh, $str1);
fclose($dh);

$dh = fopen ($datei,"r+");
echo "content: ".fread($dh, filesize($datei))."<br>";
echo "pointer after fread at: ".ftell($dh)."<br>";
ftruncate($dh, 0);
echo "pointer after truncate at: ".ftell($dh)."<br>";
fwrite($dh, $str2);
echo "pointer after fwrite at: ".ftell($dh)."<br>";
rewind($dh);
echo "pointer after rewind at: ".ftell($dh)."<br>";
$str = fread($dh, 6);
echo "content: $str<br>in ASCII: ";
for($i = 0; $i < 6; $i++)
 echo ord($str{$i})."-";
fclose($dh);

/*
   OUTPUT:
   content: 1234
   pointer after fread at: 4
   pointer after truncate at: 4
   pointer after fwrite at: 6
   pointer after rewind at: 0
   content: 56
   in ASCII: 0-0-0-0-53-54
*/
?>

So not only ftruncate is filling an empty file up with NULLs as in the note before. Fread is filling leading space with NULLs too.
Masoud
пред 5 години
The problem that rc at opelgt dot org mentioned seems completely logical.

When pointer is at offset 4 and you truncate file, the pointer is still at offset 4.

So when you write(), the first 4 bytes are filled with null byte by Operating System - There is nothing wrong by PHP. And it's filled with null byte, because there is data on disk and that needs to be cleared with zero bits.

Even though this is a Operating System's gotcha, to avoid data corruption, PHP Docs should mention it clearly. Also it would be nice if PHP automatically sets the pointer's offset to SEEK_END  after truncating to an smaller size to fool-proof it.
eurosat7 at yahoo dot de
пред 14 години
If you want to ftruncate but keep the end:
<?php
    function ftruncatestart($filename,$maxfilesize){
        $size=filesize($filename);
        if ($size<$maxfilesize*1.0) return;
        $maxfilesize=$maxfilesize*0.5; //we don't want to do it too often...
        $fh=fopen($filename,"r+");
        $start=ftell($fh);
        fseek($fh,-$maxfilesize,SEEK_END);
        $drop=fgets($fh);
        $offset=ftell($fh);
        for ($x=0;$x<$maxfilesize;$x++){
            fseek($fh,$x+$offset);
            $c=fgetc($fh);
            fseek($fh,$x);
            fwrite($fh,$c);
        }
        ftruncate($fh,$maxfilesize-strlen($drop));
        fclose($fh);
    }
?>
It will not just cut it but search for a newline so you avoid corrupting your csv or logfiles. But I don't know if you will stress the reading head of your drive. ;)
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.