ftruncate
ftruncate(resource $stream, int $size): bool
Truncates or extends an open stream to a given length in place: shrink — bytes past the offset are dropped; grow — the file becomes larger and the new gap reads back as zero bytes (a sparse file). Combined with fseek+fwrite this is the common in-place rewrite pattern.
C C23
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(void) {
char path[] = "/tmp/tru_c_XXXXXX";
int fd = mkstemp(path);
char payload[100];
memset(payload, 'A', sizeof payload);
write(fd, payload, sizeof payload); // 100 bytes
ftruncate(fd, 20); // shrink: bytes past offset 20 are dropped
lseek(fd, 0, SEEK_SET);
char buf[256] = {0};
ssize_t n = read(fd, buf, sizeof buf - 1);
printf("%zd\n", n); // 20
printf("%s\n", buf); // 20 x 'A'
ftruncate(fd, 200); // grow: the gap reads back as zero bytes
lseek(fd, 100, SEEK_SET);
memset(buf, 0, sizeof buf);
n = read(fd, buf, 100);
int zeros = 1;
for (ssize_t i = 0; i < n; i++) zeros = zeros && (buf[i] == 0);
printf("%zd\n", n); // 100
printf("%d\n", zeros); // 1
close(fd);
unlink(path);
return 0;
}
20 AAAAAAAAAAAAAAAAAAAA 100 1
C++ C++26
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
int main() {
char path[] = "/tmp/tru_cpp_XXXXXX";
int fd = mkstemp(path);
char payload[100];
memset(payload, 'A', sizeof payload);
write(fd, payload, sizeof payload); // 100 bytes
ftruncate(fd, 20); // shrink: bytes past offset 20 are dropped
lseek(fd, 0, SEEK_SET);
char buf[256] = {0};
ssize_t n = read(fd, buf, sizeof buf - 1);
std::printf("%zd\n", n); // 20
std::printf("%s\n", buf); // 20 x 'A'
ftruncate(fd, 200); // grow: the gap reads back as zero bytes
lseek(fd, 100, SEEK_SET);
memset(buf, 0, sizeof buf);
n = read(fd, buf, 100);
int zeros = 1;
for (ssize_t i = 0; i < n; i++) zeros = zeros && (buf[i] == 0);
std::printf("%zd\n", n); // 100
std::printf("%d\n", zeros); // 1
close(fd);
unlink(path);
return 0;
}
20 AAAAAAAAAAAAAAAAAAAA 100 1
C# v11.0.100
using System.IO;
using System.Text;
var path = Path.GetTempFileName();
using (var fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite))
{
var payload = Encoding.ASCII.GetBytes(new string('A', 100));
fs.Write(payload, 0, payload.Length); // 100 bytes
fs.SetLength(20); // shrink: bytes past offset 20 are dropped
fs.Position = 0;
var buf = new byte[1000];
int n = fs.Read(buf, 0, buf.Length);
Console.WriteLine(n); // 20
Console.WriteLine(Encoding.ASCII.GetString(buf, 0, n));
fs.SetLength(200); // grow: the gap reads back as zero bytes
fs.Position = 100;
Array.Fill(buf, (byte)1);
n = fs.Read(buf, 0, 100);
int zeros = 0;
for (int i = 0; i < n; i++) if (buf[i] == 0) zeros++;
Console.WriteLine(n); // 100
Console.WriteLine(zeros); // 100
}
File.Delete(path);
20 AAAAAAAAAAAAAAAAAAAA 100 100
Go v1.27.4
package main
import (
"bytes"
"fmt"
"io"
"os"
)
func main() {
path := fmt.Sprintf("%s/tru_go_%d", os.TempDir(), os.Getpid())
f, _ := os.Create(path)
f.Write(bytes.Repeat([]byte("A"), 100)) // 100 bytes
f.Truncate(20) // shrink: bytes past offset 20 are dropped
f.Seek(0, io.SeekStart)
data, _ := io.ReadAll(f)
fmt.Println(len(data)) // 20
fmt.Println(string(data))
f.Truncate(200) // grow: the gap reads back as zero bytes
f.Seek(100, io.SeekStart)
gap, _ := io.ReadAll(f)
fmt.Println(len(gap)) // 100
fmt.Println(bytes.Count(gap, []byte{0})) // 100
f.Close()
os.Remove(path)
}
20 AAAAAAAAAAAAAAAAAAAA 100 100
Java v27.0.1
import java.io.RandomAccessFile;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws Exception {
Path p = Files.createTempFile("tru", ".dat");
RandomAccessFile raf = new RandomAccessFile(p.toFile(), "rw");
byte[] payload = new byte[100];
Arrays.fill(payload, (byte) 'A');
raf.write(payload); // 100 bytes
raf.setLength(20); // shrink: bytes past offset 20 are dropped
raf.seek(0);
byte[] buf = new byte[1000];
int n = raf.read(buf);
System.out.println(n); // 20
System.out.println(new String(buf, 0, n)); // 20 x 'A'
raf.setLength(200); // grow: the gap reads back as zero bytes
raf.seek(100);
Arrays.fill(buf, (byte) 1);
n = raf.read(buf, 0, 100);
int zeros = 0;
for (int i = 0; i < n; i++) if (buf[i] == 0) zeros++;
System.out.println(n); // 100
System.out.println(zeros); // 100
raf.close();
Files.delete(p);
}
}
20 AAAAAAAAAAAAAAAAAAAA 100 100
JavaScript v26.13.1
const fs = require("fs");
const os = require("os");
const path = require("path");
const file = path.join(fs.mkdtempSync(os.tmpdir() + "/tru_"), "data.bin");
const fd = fs.openSync(file, "w+");
fs.writeSync(fd, Buffer.alloc(100, 65)); // 65 = 'A': 100 bytes
fs.ftruncateSync(fd, 20); // shrink
let data = Buffer.alloc(1000);
let n = fs.readSync(fd, data, 0, 1000, 0);
console.log(n); // 20
console.log(data.toString("latin1", 0, n)); // 20 x 'A'
fs.ftruncateSync(fd, 200); // grow: the gap reads back as zero bytes
let gap = Buffer.alloc(100, 1);
n = fs.readSync(fd, gap, 0, 100, 100);
let zeros = 0;
for (let i = 0; i < n; i++) if (gap[i] === 0) zeros++;
console.log(n); // 100
console.log(zeros); // 100
fs.closeSync(fd);
fs.unlinkSync(file);
20 AAAAAAAAAAAAAAAAAAAA 100 100
PHP v8.6.0
$path = tempnam(sys_get_temp_dir(), 'tru_');
$f = fopen($path, 'w+');
fwrite($f, str_repeat('A', 100)); // 100 bytes
ftruncate($f, 20); // shrink: bytes past offset 20 are dropped
rewind($f);
$data = fread($f, 1000);
echo strlen($data), "\n"; // 20
echo $data, "\n"; // 20 x 'A'
ftruncate($f, 200); // grow: the gap reads back as zero bytes
fseek($f, 100);
$gap = fread($f, 100);
echo strlen($gap), "\n"; // 100
echo substr_count($gap, "\0"), "\n"; // 100 zero bytes
fclose($f);
unlink($path);
20 AAAAAAAAAAAAAAAAAAAA 100 100
Python v3.15.2
import os
import tempfile
fd, path = tempfile.mkstemp(prefix="tru_")
os.write(fd, b"A" * 100) # 100 bytes
os.ftruncate(fd, 20) # shrink: bytes past offset 20 are dropped
os.lseek(fd, 0, 0)
data = os.read(fd, 1000)
print(len(data)) # 20
print(data.decode()) # 20 x 'A'
os.ftruncate(fd, 200) # grow: the gap reads back as zero bytes
os.lseek(fd, 100, 0)
gap = os.read(fd, 100)
print(len(gap)) # 100
print(gap.count(0)) # 100 zero bytes
os.close(fd)
os.unlink(path)
20 AAAAAAAAAAAAAAAAAAAA 100 100
Rust v1.99.1
use std::fs::File;
use std::io::{Read, Seek, SeekFrom, Write};
fn main() {
let path = std::env::temp_dir().join(format!("tru_rs_{}", std::process::id()));
let mut f = File::options().read(true).write(true).create(true).truncate(true).open(&path).unwrap();
f.write_all(&[b'A'; 100]).unwrap(); // 100 bytes
f.set_len(20).unwrap(); // shrink: bytes past offset 20 are dropped
f.seek(SeekFrom::Start(0)).unwrap();
let mut data = Vec::new();
f.read_to_end(&mut data).unwrap();
println!("{}", data.len()); // 20
println!("{}", String::from_utf8(data).unwrap());
f.set_len(200).unwrap(); // grow: the gap reads back as zero bytes
f.seek(SeekFrom::Start(100)).unwrap();
let mut gap = Vec::new();
f.read_to_end(&mut gap).unwrap();
println!("{}", gap.len()); // 100
println!("{}", gap.iter().filter(|&&b| b == 0).count()); // 100
drop(f);
std::fs::remove_file(&path).unwrap();
}
20 AAAAAAAAAAAAAAAAAAAA 100 100
TypeScript v26.13.1
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
const file = path.join(fs.mkdtempSync(`${os.tmpdir()}/tru_`), "data.bin");
const fd = fs.openSync(file, "w+");
fs.writeSync(fd, Buffer.alloc(100, 65)); // 65 = 'A': 100 bytes
fs.ftruncateSync(fd, 20); // shrink
let data = Buffer.alloc(1000);
let n = fs.readSync(fd, data, 0, 1000, 0);
console.log(n); // 20
console.log(data.toString("latin1", 0, n)); // 20 x 'A'
fs.ftruncateSync(fd, 200); // grow: the gap reads back as zero bytes
let gap = Buffer.alloc(100, 1);
n = fs.readSync(fd, gap, 0, 100, 100);
let zeros = 0;
for (let i = 0; i < n; i++) if (gap[i] === 0) zeros++;
console.log(n); // 100
console.log(zeros); // 100
fs.closeSync(fd);
fs.unlinkSync(file);
20 AAAAAAAAAAAAAAAAAAAA 100 100
Language differences
PHP: ftruncate($stream, $size) resizes the current stream in place; shrink — trailing bytes are dropped, grow — the gap reads back as \0; the call does NOT move the file pointer (the example rewinds/seeks explicitly); paired with fseek+fwrite it is the common in-place rewrite pattern for large files.
C/C++: ftruncate(2) (<unistd.h>) works on an open fd; growing creates a sparse file — holes occupy no physical blocks, so du reports far less than the apparent ls size.
C#: FileStream.SetLength.
Go: File.Truncate (plus the path-based os.Truncate).
Java: RandomAccessFile.setLength shrinks and grows; the NIO FileChannel.truncate only shrinks.
JavaScript: fs.ftruncateSync(fd, len).
Python: os.ftruncate(fd, len); the file object's .truncate(len) also works.
Rust: File::set_len.
TypeScript: same as JS.
Caveat: truncation is NOT secure erasure — the shrunk region is only unmapped and its disk blocks may survive; destroy data by overwriting it.