Taskcore
Truncate a file
Also called resize a file, set the size of a file, shorten a file, extend a file with zero bytes, ftruncate.
Set the size of an existing file to a given number of bytes. Cut the bytes after the new end, or add zero bytes up to it, and do not make a file when none is there.
- Evidence
- Code in 10 languages
Task
Set the size of the existing file at path to length bytes. If the file was longer, the bytes after length are gone. If the file was shorter, the file grows, and the new bytes are zero bytes. The bytes before length do not change.
Report an error, and change no file, when no file is at path, when path is a directory, and when length is less than 0. The first case is important: many ways to open a file for writing make a new file when there is none. A truncate must not do that.
POSIX gives the rule for the two directions: "If the file previously was larger than length , the extra data is discarded. If the file was previously shorter than length , its size is increased, and the extended area appears as if it were zero-filled." The Linux manual says the same, and adds: "The file offset is not changed." The pitfalls show why that last sentence is important.
SQL, regular expressions, HTML and CSS do not apply, because they do not change the size of a file.
Solutions
Each language has a call that sets the size of a file by its path or through an open file. Most of them do the two directions, but not all.
- Python.
os.truncate(path, length). "Truncate the file corresponding to path , so that it is at most length bytes in size." But the call also makes a file longer: on Linux and macOS, a greater length adds zero bytes, and the tests check this. For a file that is open,f.truncate(size)does the same: "This resizing can extend or reduce the current file size. In case of extension, the contents of the new file area depend on the platform (on most systems, additional bytes are zero-filled)." Each error is anOSError. - JavaScript and TypeScript (Node.js).
fsPromises.truncate(path, length). "Truncates (shortens or extends the length) of the content at path to len bytes." Node does not report an error for a negative length: "If len is negative then 0 will be used." So the code throws aRangeErrorfirst, because a negative length is a mistake of the caller, and Node would make the file empty. - Java.
FileChannel.open(path, StandardOpenOption.WRITE)opens the file with noCREATE, so a missing file givesNoSuchFileException.truncate(length)makes the file shorter, but it does not make it longer: "If the given size is greater than or equal to the file's current size then the file is not modified." So for a greater length, the code writes one zero byte atlength - 1. - C#.
new FileStream(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite)and thenstream.SetLength(length).FileMode.Opendoes not make a file. "If the given value is less than the current length of the stream, the stream is truncated." The code throws anIOExceptionfor a directory, andArgumentOutOfRangeException.ThrowIfNegativefor a negative length. - Go.
os.Truncate(path, length). "Truncate changes the size of the named file. If the file is a symbolic link, it changes the size of the link's target. If there is an error, it will be of type *PathError ." For an open*os.File, the method isf.Truncate(size). - Rust.
OpenOptions::new().write(true).open(path)and thenfile.set_len(length). "Truncates or extends the underlying file, updating the size of this file to become size . If the size is less than the current file’s size, then the file will be shrunk. If it is greater than the current file’s size, then the file will be extended to size and have all of the intermediate data filled in with 0s." The length is au64, so a negative length is not possible. - C. POSIX
truncate(path, length), withftruncate(fd, length)for an open file. It returns -1 and setserrno, for example "[EISDIR] The named file is a directory." ISO C has no call that sets the size of a file. - C++.
std::filesystem::resize_file(path, length, ec). It "Changes the size of the regular file named by p as if by POSIX truncate : if the file size was previously larger than new_size , the remainder of the file is discarded. If the file was previously smaller than new_size , the file size is increased and the new area appears as if zero-filled." - Bash. POSIX has no
truncateutility, so the code usesdd if=/dev/null of="$path" bs=1 seek="$length". The input is empty, so dd writes nothing, and then: "If the input file is empty and either the size of the seek is greater than the previous size of the output file or the output file did not previously exist, the size of the output file shall be set to the file offset after the seek." With noconv=notrunc, dd also cuts the bytes after the seek. dd makes a missing file, so the function checks for a missing file, for a directory and for a length that is not a whole number first, and returns status 1.
On Windows, the system call that sets the size of a file is SetEndOfFile. It "Sets the physical file size for the specified file to the current position of the file pointer", so a program moves the file pointer to the new size first.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl. Each test writes the file in a new temporary directory, calls the function, and checks all the bytes of the file.
shrink:alpha beta\nto 5 bytes givesalpha.extend:alphato 8 bytes givesalphaand three zero bytes.same-length: a length equal to the size changes nothing.to-zero: a length of 0 gives an empty file.empty-file: an empty file to 3 bytes gives three zero bytes.name-with-spaces:my notes.txt. A shell solution must quote the name.- Errors, in
cases/errors.jsonl: a missing file gives not-found, and the test checks that no file is made. A directory gives is-a-directory, and a length of -1 gives invalid-length, in the languages where the type of the length lets the caller give one.
The native tests also check what happens to a stream that has the file open. A stream in append mode writes its next line at the new end. A stream at a position after the new end writes at that position, and a hole of zero bytes comes before the new data.
Pitfalls
- A truncate that makes a new file.
open(path, "w")in Python makes the file empty, but it also makes a file when there is none: "'w' open for writing, truncating the file first". So a typing mistake in the path gives a new empty file, and no error:
This code runs but gives a wrong answer on purpose.
import os
import tempfile
def truncate_with_w(path):
with open(path, "w"): # "w" makes a file when there is none
pass
with tempfile.TemporaryDirectory() as dir:
path = os.path.join(dir, "missing.txt")
truncate_with_w(path)
print("exists:", os.path.exists(path))
exists: True
The same is true for : > "$path" in a shell, for RandomAccessFile in Java with the mode "rw" ("If the file does not already exist then an attempt will be made to create it."), and for FileMode.Create in C#. Use a call that takes a path and does not open the file for writing, such as os.truncate, or open with no create flag. Also, open with "w" can only give a length of 0.
- A writer that keeps its old position. A truncate does not move the position of a stream that has the file open. POSIX says for
ftruncate: "The value of the seek pointer shall not be modified by a call to ftruncate ()." So when one program empties a log file and the program that writes the log has it open with no append mode, the next write goes to the old position. The bytes before it read as zero bytes, and the file is as large as before:
import os
import tempfile
with tempfile.TemporaryDirectory() as dir:
path = os.path.join(dir, "app.log")
log = open(path, "w") # no O_APPEND
log.write("old line 1\nold line 2\n")
log.flush()
os.truncate(path, 0) # another program empties the log
log.write("new\n")
log.close()
with open(path, "rb") as f:
data = f.read()
print("size:", len(data))
print("zero bytes:", data.count(0))
size: 26
zero bytes: 22
Open a log file in append mode. Python says that "a" is "for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position)". With "a" in place of "w", the same program gives a file of 4 bytes:
import os
import tempfile
with tempfile.TemporaryDirectory() as dir:
path = os.path.join(dir, "app.log")
log = open(path, "a") # O_APPEND: each write goes to the end
log.write("old line 1\nold line 2\n")
log.flush()
os.truncate(path, 0)
log.write("new\n")
log.close()
with open(path, "rb") as f:
print(f.read())
b'new\n'
-
Append mode in .NET is not the same.
FileMode.Append"Opens the file if it exists and seeks to the end of the file, or creates a new file." The stream goes to the end one time, when it opens the file, and then it writes at its own position. On Linux and macOS, the C# native test shows that a write after a truncate to 0 gives a hole of zero bytes, as in the"w"example above. -
A truncate that cannot make a file longer. Java
FileChannel.truncatedoes nothing when the size is greater than the size of the file.RandomAccessFile.setLengthdoes make the file longer, but "The contents of the extended portion of the file are not defined." Test the two directions. -
A negative length. Most calls report an error. Node uses 0, so a mistake in a calculation of the length makes the file empty. Check the length before the call.
-
A truncate in the middle of a character. The length is in bytes, not in characters. A truncate of
café(5 bytes in UTF-8) to 4 bytes cuts theéinto one byte, and the file is not valid UTF-8 after it. To cut text, find the byte offset of a character boundary first.
Related tasks
- Get the size of a file
- Append to a file
- Copy a file
- Delete a file
- Check whether a file exists
- Read and write with buffers
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/truncate-a-file/.
import os
def truncate_file(path: str | os.PathLike, length: int) -> None:
"""Sets the size of the existing file at path to length bytes.
os.truncate cuts the bytes after length, or adds zero bytes up to length.
It does not make a missing file. Each error comes out as an OSError:
FileNotFoundError, IsADirectoryError, or EINVAL for a length under 0.
"""
os.truncate(path, length)
test_truncate_file.py 62 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/truncate-a-file/.
import errno
import os
from pathlib import Path
import pytest
from truncate_file import truncate_file
# name: (path, length, content before, content after)
CASES = {
"shrink": ("a.txt", 5, b"alpha beta\n", b"alpha"),
"extend": ("a.txt", 8, b"alpha", b"alpha\0\0\0"),
"same-length": ("a.txt", 6, b"alpha\n", b"alpha\n"),
"to-zero": ("a.txt", 0, b"alpha\n", b""),
"empty-file": ("a.txt", 3, b"", b"\0\0\0"),
"name-with-spaces": ("my notes.txt", 2, b"alpha\n", b"al"),
}
@pytest.mark.parametrize("name", CASES)
def test_cases(tmp_path: Path, name: str) -> None:
rel, length, before, after = CASES[name]
path = tmp_path / rel
path.write_bytes(before)
truncate_file(path, length)
assert path.read_bytes() == after
def test_errors(tmp_path: Path) -> None:
with pytest.raises(FileNotFoundError):
truncate_file(tmp_path / "a.txt", 0)
assert not (tmp_path / "a.txt").exists()
(tmp_path / "dir").mkdir()
with pytest.raises(IsADirectoryError):
truncate_file(tmp_path / "dir", 0)
(tmp_path / "a.txt").write_bytes(b"alpha\n")
with pytest.raises(OSError) as e:
truncate_file(tmp_path / "a.txt", -1)
assert e.value.errno == errno.EINVAL
assert (tmp_path / "a.txt").read_bytes() == b"alpha\n"
def test_open_in_append_mode(tmp_path: Path) -> None:
path = tmp_path / "app.log"
path.write_bytes(b"alpha beta\n")
with open(path, "ab") as log:
truncate_file(path, 0)
log.write(b"new\n")
assert path.read_bytes() == b"new\n"
def test_open_after_the_new_end(tmp_path: Path) -> None:
path = tmp_path / "data.bin"
path.write_bytes(b"alpha beta\n")
with open(path, "r+b") as f:
f.seek(0, os.SEEK_END)
truncate_file(path, 5)
f.write(b"X")
assert path.read_bytes() == b"alpha" + b"\0" * 6 + b"X"
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/truncate-a-file/.
#include "truncate_file.hpp"
void truncate_file(const std::filesystem::path& path, std::uintmax_t length, std::error_code& ec) {
// resize_file works as POSIX truncate: it cuts the bytes after length,
// or adds zero bytes up to length, and it does not make a missing file.
std::filesystem::resize_file(path, length, ec);
}
truncate_file.hpp 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/truncate-a-file/.
#pragma once
#include <cstdint>
#include <filesystem>
#include <system_error>
// Sets the size of the existing file at path to length bytes, with
// std::filesystem::resize_file. Sets ec on an error, for example
// std::errc::no_such_file_or_directory or std::errc::is_a_directory. length
// is unsigned, so it cannot be under 0.
void truncate_file(const std::filesystem::path& path, std::uintmax_t length, std::error_code& ec);
test_truncate_file.cpp 101 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/truncate-a-file/.
#include <cstdio>
#include <filesystem>
#include <fstream>
#include <iterator>
#include <string>
#include <system_error>
#include "truncate_file.hpp"
namespace fs = std::filesystem;
using namespace std::string_literals;
namespace {
const fs::path dir = "truncate_file_tree";
int failures = 0;
void put(const fs::path& p, const std::string& text) { std::ofstream(p, std::ios::binary) << text; }
std::string get(const fs::path& p) {
std::ifstream in(p, std::ios::binary);
return {std::istreambuf_iterator<char>(in), {}};
}
void expect(bool ok, const char* what) {
if (!ok) {
std::fprintf(stderr, "%s\n", what);
++failures;
}
}
void fresh() {
fs::remove_all(dir);
fs::create_directories(dir);
}
void run_case(const char* name, const char* path, std::uintmax_t length, const std::string& before,
const std::string& after) {
fresh();
put(dir / path, before);
std::error_code ec;
truncate_file(dir / path, length, ec);
expect(!ec && get(dir / path) == after, name);
}
void test_errors() {
fresh();
std::error_code ec;
truncate_file(dir / "a.txt", 0, ec);
expect(ec == std::errc::no_such_file_or_directory, "missing");
expect(!fs::exists(fs::symlink_status(dir / "a.txt")), "no file made");
fs::create_directory(dir / "dir");
truncate_file(dir / "dir", 0, ec);
expect(ec == std::errc::is_a_directory, "directory");
}
void test_open() {
fresh();
put(dir / "app.log", "alpha beta\n");
{
std::ofstream log(dir / "app.log", std::ios::binary | std::ios::app);
std::error_code ec;
truncate_file(dir / "app.log", 0, ec);
expect(!ec, "append truncate");
log << "new\n";
}
expect(get(dir / "app.log") == "new\n", "append data");
put(dir / "data.bin", "alpha beta\n");
{
std::fstream f(dir / "data.bin", std::ios::binary | std::ios::in | std::ios::out);
f.seekp(0, std::ios::end);
std::error_code ec;
truncate_file(dir / "data.bin", 5, ec);
expect(!ec, "hole truncate");
f << 'X';
}
expect(get(dir / "data.bin") == "alpha\0\0\0\0\0\0X"s, "hole data");
}
} // namespace
int main() {
run_case("shrink", "a.txt", 5, "alpha beta\n", "alpha");
run_case("extend", "a.txt", 8, "alpha", "alpha\0\0\0"s);
run_case("same-length", "a.txt", 6, "alpha\n", "alpha\n");
run_case("to-zero", "a.txt", 0, "alpha\n", "");
run_case("empty-file", "a.txt", 3, "", "\0\0\0"s);
run_case("name-with-spaces", "my notes.txt", 2, "alpha\n", "al");
test_errors();
test_open();
fs::remove_all(dir);
if (failures != 0) {
std::fprintf(stderr, "%d failures\n", failures);
return 1;
}
std::puts("ok");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/truncate-a-file/.
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public final class TruncateFile {
private TruncateFile() {}
/**
* Sets the size of the existing file at path to length bytes.
*
* <p>The channel is opened with WRITE and no CREATE, so a missing file gives
* NoSuchFileException. FileChannel.truncate only makes a file shorter: for a greater size, the
* file is not modified. So to extend the file, the method writes one zero byte at length - 1, and
* the bytes before it read as zero. RandomAccessFile.setLength extends too, but its mode "rw"
* makes a missing file.
*/
public static void truncate(Path path, long length) throws IOException {
if (length < 0) {
throw new IllegalArgumentException("length must be 0 or more: " + length);
}
try (FileChannel ch = FileChannel.open(path, StandardOpenOption.WRITE)) {
if (length < ch.size()) {
ch.truncate(length);
} else if (length > ch.size()) {
ch.write(ByteBuffer.wrap(new byte[1]), length - 1);
}
}
}
}
TruncateFileTest.java 79 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/truncate-a-file/.
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystemException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class TruncateFileTest {
@TempDir Path dir;
private static byte[] bytes(String s) {
return s.replace("EMPTY", "").replace("\\n", "\n").replace("\\0", "\0").getBytes(StandardCharsets.UTF_8);
}
@ParameterizedTest(name = "{0}")
@CsvSource(
delimiter = '|',
value = {
"shrink | a.txt | 5 | alpha beta\\n | alpha",
"extend | a.txt | 8 | alpha | alpha\\0\\0\\0",
"same-length | a.txt | 6 | alpha\\n | alpha\\n",
"to-zero | a.txt | 0 | alpha\\n | EMPTY",
"empty-file | a.txt | 3 | EMPTY | \\0\\0\\0",
"name-with-spaces | my notes.txt | 2 | alpha\\n | al",
})
void cases(String name, String rel, long length, String before, String after) throws IOException {
Path path = Files.write(dir.resolve(rel), bytes(before));
TruncateFile.truncate(path, length);
assertArrayEquals(bytes(after), Files.readAllBytes(path), name);
}
@Test
void errors() throws IOException {
assertThrows(NoSuchFileException.class, () -> TruncateFile.truncate(dir.resolve("a.txt"), 0));
assertFalse(Files.exists(dir.resolve("a.txt")));
Path sub = Files.createDirectory(dir.resolve("dir"));
assertThrows(FileSystemException.class, () -> TruncateFile.truncate(sub, 0));
Path path = Files.writeString(dir.resolve("a.txt"), "alpha\n");
assertThrows(IllegalArgumentException.class, () -> TruncateFile.truncate(path, -1));
assertEquals("alpha\n", Files.readString(path));
}
@Test
void openInAppendMode() throws IOException {
Path path = Files.writeString(dir.resolve("app.log"), "alpha beta\n");
try (OutputStream log = Files.newOutputStream(path, StandardOpenOption.APPEND)) {
TruncateFile.truncate(path, 0);
log.write("new\n".getBytes(StandardCharsets.UTF_8));
}
assertEquals("new\n", Files.readString(path));
}
@Test
void openAfterTheNewEnd() throws IOException {
Path path = Files.writeString(dir.resolve("data.bin"), "alpha beta\n");
try (FileChannel f = FileChannel.open(path, StandardOpenOption.WRITE)) {
f.position(f.size());
TruncateFile.truncate(path, 5);
f.write(ByteBuffer.wrap(new byte[] {'X'}));
}
assertArrayEquals(bytes("alpha\\0\\0\\0\\0\\0\\0X"), Files.readAllBytes(path));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/truncate-a-file/.
// truncate is in POSIX, not in ISO C.
#define _POSIX_C_SOURCE 200809L
#include "truncate_file.h"
#include <unistd.h>
// POSIX truncate cuts the bytes after length, or adds zero bytes up to
// length. It does not make a missing file.
int truncate_file(const char *path, off_t length) { return truncate(path, length) == 0 ? 0 : -1; }
truncate_file.h 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/truncate-a-file/.
#ifndef TRUNCATE_FILE_H
#define TRUNCATE_FILE_H
#include <sys/types.h>
// truncate_file sets the size of the existing file at path to length bytes.
// It returns 0, or -1 with errno from truncate: ENOENT, EISDIR, or EINVAL for
// a length under 0.
int truncate_file(const char *path, off_t length);
#endif
test_truncate_file.c 107 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/truncate-a-file/.
#define _POSIX_C_SOURCE 200809L
#include "truncate_file.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
static const char *dir = "truncate_file_tree";
static int failures = 0;
static char *at(char *buf, const char *name) {
snprintf(buf, 256, "%s/%s", dir, name);
return buf;
}
static void put(const char *name, const char *data, size_t n) {
char p[256];
FILE *f = fopen(at(p, name), "wb");
if (f == NULL || fwrite(data, 1, n, f) != n || fclose(f) != 0) exit(2);
}
static int same(const char *name, const char *want, size_t n) {
char p[256], data[64];
FILE *f = fopen(at(p, name), "rb");
if (f == NULL) return 0;
size_t got = fread(data, 1, sizeof data, f);
fclose(f);
return got == n && memcmp(data, want, n) == 0;
}
static void expect(int ok, const char *what) {
if (!ok) {
fprintf(stderr, "%s\n", what);
failures++;
}
}
static void fresh(void) {
if (system("rm -rf truncate_file_tree") != 0 || mkdir(dir, 0755) != 0) exit(2);
}
static void run_case(const char *name, const char *path, off_t length, const char *before, size_t nb,
const char *after, size_t na) {
char p[256];
fresh();
put(path, before, nb);
expect(truncate_file(at(p, path), length) == 0, name);
expect(same(path, after, na), name);
}
static void test_errors(void) {
char p[256];
struct stat st;
fresh();
errno = 0;
expect(truncate_file(at(p, "a.txt"), 0) == -1 && errno == ENOENT, "missing");
expect(lstat(at(p, "a.txt"), &st) != 0, "no file made");
if (mkdir(at(p, "dir"), 0755) != 0) exit(2);
errno = 0;
expect(truncate_file(at(p, "dir"), 0) == -1 && errno == EISDIR, "directory");
put("a.txt", "alpha\n", 6);
errno = 0;
expect(truncate_file(at(p, "a.txt"), -1) == -1 && errno == EINVAL, "negative");
expect(same("a.txt", "alpha\n", 6), "no change");
}
static void test_open(void) {
char p[256];
fresh();
put("app.log", "alpha beta\n", 11);
int log = open(at(p, "app.log"), O_WRONLY | O_APPEND);
expect(log >= 0 && truncate_file(p, 0) == 0 && write(log, "new\n", 4) == 4, "append");
close(log);
expect(same("app.log", "new\n", 4), "append data");
put("data.bin", "alpha beta\n", 11);
int f = open(at(p, "data.bin"), O_WRONLY);
expect(f >= 0 && lseek(f, 0, SEEK_END) == 11, "seek");
expect(truncate_file(p, 5) == 0 && write(f, "X", 1) == 1, "hole");
close(f);
expect(same("data.bin", "alpha\0\0\0\0\0\0X", 12), "hole data");
}
int main(void) {
run_case("shrink", "a.txt", 5, "alpha beta\n", 11, "alpha", 5);
run_case("extend", "a.txt", 8, "alpha", 5, "alpha\0\0\0", 8);
run_case("same-length", "a.txt", 6, "alpha\n", 6, "alpha\n", 6);
run_case("to-zero", "a.txt", 0, "alpha\n", 6, "", 0);
run_case("empty-file", "a.txt", 3, "", 0, "\0\0\0", 3);
run_case("name-with-spaces", "my notes.txt", 2, "alpha\n", 6, "al", 2);
test_errors();
test_open();
if (system("rm -rf truncate_file_tree") != 0) failures++;
if (failures != 0) {
fprintf(stderr, "%d failures\n", failures);
return 1;
}
puts("ok");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/truncate-a-file/.
public static class TruncateFile
{
/// <summary>
/// Sets the size of the existing file at path to length bytes. FileMode.Open
/// does not make a missing file, so a missing file gives FileNotFoundException.
/// FileStream.SetLength cuts the bytes after length, or adds zero bytes up to
/// length, and gives ArgumentOutOfRangeException for a length under 0. A
/// directory at path gives an IOException.
/// </summary>
public static void Truncate(string path, long length)
{
ArgumentOutOfRangeException.ThrowIfNegative(length);
if (Directory.Exists(path))
{
throw new IOException($"Is a directory: '{path}'");
}
using var stream = new FileStream(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite);
stream.SetLength(length);
}
}
TruncateFileTests.cs 62 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/truncate-a-file/.
using System.Text;
using Xunit;
public sealed class TruncateFileTests : IDisposable
{
private readonly string dir = Directory.CreateTempSubdirectory("truncate-file-").FullName;
public void Dispose() => Directory.Delete(dir, recursive: true);
// name, path, length, content before, content after
public static TheoryData<string, string, long, string, string> Cases => new()
{
{ "shrink", "a.txt", 5, "alpha beta\n", "alpha" },
{ "extend", "a.txt", 8, "alpha", "alpha\0\0\0" },
{ "same-length", "a.txt", 6, "alpha\n", "alpha\n" },
{ "to-zero", "a.txt", 0, "alpha\n", "" },
{ "empty-file", "a.txt", 3, "", "\0\0\0" },
{ "name-with-spaces", "my notes.txt", 2, "alpha\n", "al" },
};
[Theory]
[MemberData(nameof(Cases))]
public void Truncates(string name, string rel, long length, string before, string after)
{
string path = Path.Combine(dir, rel);
File.WriteAllBytes(path, Encoding.UTF8.GetBytes(before));
TruncateFile.Truncate(path, length);
Assert.True(Encoding.UTF8.GetBytes(after).AsSpan().SequenceEqual(File.ReadAllBytes(path)), name);
}
[Fact]
public void Errors()
{
string path = Path.Combine(dir, "a.txt");
Assert.Throws<FileNotFoundException>(() => TruncateFile.Truncate(path, 0));
Assert.False(File.Exists(path));
string sub = Directory.CreateDirectory(Path.Combine(dir, "dir")).FullName;
Assert.Throws<IOException>(() => TruncateFile.Truncate(sub, 0));
File.WriteAllText(path, "alpha\n");
Assert.Throws<ArgumentOutOfRangeException>(() => TruncateFile.Truncate(path, -1));
Assert.Equal("alpha\n", File.ReadAllText(path));
}
// FileMode.Append does not open the file with O_APPEND: the stream seeks
// to the end at the open and then writes at its own position. So after a
// truncate to 0, the next write is at the old end, after a hole.
[Fact]
public void OpenInAppendMode()
{
string path = Path.Combine(dir, "app.log");
File.WriteAllText(path, "alpha beta\n");
using (var log = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
TruncateFile.Truncate(path, 0);
log.Write("new\n"u8);
}
Assert.Equal(new string('\0', 11) + "new\n", File.ReadAllText(path));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/truncate-a-file/.
import { truncate } from "node:fs/promises";
/**
* Sets the size of the existing file at path to length bytes. truncate cuts
* the bytes after length, or adds zero bytes up to length, and it does not
* make a missing file. It uses 0 for a negative length, so the code throws a
* RangeError first. Each other error, such as ENOENT or EISDIR, is thrown.
*/
export async function truncateFile(path, length) {
if (!Number.isSafeInteger(length) || length < 0) {
throw new RangeError(`length must be an integer, 0 or more: ${length}`);
}
await truncate(path, length);
}
truncateFile.test.js 78 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/truncate-a-file/.
import { test } from "node:test";
import assert from "node:assert/strict";
import { existsSync } from "node:fs";
import { mkdir, mkdtemp, open, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { truncateFile } from "./truncateFile.js";
async function withDir(fn) {
const dir = await mkdtemp(join(tmpdir(), "truncate-file-"));
try {
await fn(dir);
} finally {
await rm(dir, { recursive: true, force: true });
}
}
// name: [path, length, content before, content after]
const cases = [
["shrink", "a.txt", 5, "alpha beta\n", "alpha"],
["extend", "a.txt", 8, "alpha", "alpha\0\0\0"],
["same-length", "a.txt", 6, "alpha\n", "alpha\n"],
["to-zero", "a.txt", 0, "alpha\n", ""],
["empty-file", "a.txt", 3, "", "\0\0\0"],
["name-with-spaces", "my notes.txt", 2, "alpha\n", "al"],
];
for (const [name, rel, length, before, after] of cases) {
test(name, () =>
withDir(async (dir) => {
const path = join(dir, rel);
await writeFile(path, before);
await truncateFile(path, length);
assert.deepEqual(await readFile(path), Buffer.from(after));
}));
}
test("errors", () =>
withDir(async (dir) => {
await assert.rejects(truncateFile(join(dir, "a.txt"), 0), { code: "ENOENT" });
assert.equal(existsSync(join(dir, "a.txt")), false);
await mkdir(join(dir, "dir"));
await assert.rejects(truncateFile(join(dir, "dir"), 0), { code: "EISDIR" });
await writeFile(join(dir, "a.txt"), "alpha\n");
await assert.rejects(truncateFile(join(dir, "a.txt"), -1), RangeError);
assert.equal(await readFile(join(dir, "a.txt"), "utf8"), "alpha\n");
}));
test("open in append mode", () =>
withDir(async (dir) => {
const path = join(dir, "app.log");
await writeFile(path, "alpha beta\n");
const log = await open(path, "a");
try {
await truncateFile(path, 0);
await log.write("new\n");
} finally {
await log.close();
}
assert.equal(await readFile(path, "utf8"), "new\n");
}));
test("open after the new end", () =>
withDir(async (dir) => {
const path = join(dir, "data.bin");
await writeFile(path, "alpha beta\n");
const f = await open(path, "r+");
try {
await truncateFile(path, 5);
await f.write("X", 11);
} finally {
await f.close();
}
assert.deepEqual(await readFile(path), Buffer.from("alpha\0\0\0\0\0\0X"));
}));
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/truncate-a-file/.
import { truncate } from "node:fs/promises";
/**
* Sets the size of the existing file at path to length bytes. truncate cuts
* the bytes after length, or adds zero bytes up to length, and it does not
* make a missing file. It uses 0 for a negative length, so the code throws a
* RangeError first. Each other error, such as ENOENT or EISDIR, is thrown.
*/
export async function truncateFile(path: string, length: number): Promise<void> {
if (!Number.isSafeInteger(length) || length < 0) {
throw new RangeError(`length must be an integer, 0 or more: ${length}`);
}
await truncate(path, length);
}
truncateFile.test.ts 78 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/truncate-a-file/.
import { test } from "node:test";
import assert from "node:assert/strict";
import { existsSync } from "node:fs";
import { mkdir, mkdtemp, open, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { truncateFile } from "./truncateFile.ts";
async function withDir(fn: (dir: string) => Promise<void>): Promise<void> {
const dir = await mkdtemp(join(tmpdir(), "truncate-file-"));
try {
await fn(dir);
} finally {
await rm(dir, { recursive: true, force: true });
}
}
// name: [path, length, content before, content after]
const cases: [string, string, number, string, string][] = [
["shrink", "a.txt", 5, "alpha beta\n", "alpha"],
["extend", "a.txt", 8, "alpha", "alpha\0\0\0"],
["same-length", "a.txt", 6, "alpha\n", "alpha\n"],
["to-zero", "a.txt", 0, "alpha\n", ""],
["empty-file", "a.txt", 3, "", "\0\0\0"],
["name-with-spaces", "my notes.txt", 2, "alpha\n", "al"],
];
for (const [name, rel, length, before, after] of cases) {
test(name, () =>
withDir(async (dir) => {
const path = join(dir, rel);
await writeFile(path, before);
await truncateFile(path, length);
assert.deepEqual(await readFile(path), Buffer.from(after));
}));
}
test("errors", () =>
withDir(async (dir) => {
await assert.rejects(truncateFile(join(dir, "a.txt"), 0), { code: "ENOENT" });
assert.equal(existsSync(join(dir, "a.txt")), false);
await mkdir(join(dir, "dir"));
await assert.rejects(truncateFile(join(dir, "dir"), 0), { code: "EISDIR" });
await writeFile(join(dir, "a.txt"), "alpha\n");
await assert.rejects(truncateFile(join(dir, "a.txt"), -1), RangeError);
assert.equal(await readFile(join(dir, "a.txt"), "utf8"), "alpha\n");
}));
test("open in append mode", () =>
withDir(async (dir) => {
const path = join(dir, "app.log");
await writeFile(path, "alpha beta\n");
const log = await open(path, "a");
try {
await truncateFile(path, 0);
await log.write("new\n");
} finally {
await log.close();
}
assert.equal(await readFile(path, "utf8"), "new\n");
}));
test("open after the new end", () =>
withDir(async (dir) => {
const path = join(dir, "data.bin");
await writeFile(path, "alpha beta\n");
const f = await open(path, "r+");
try {
await truncateFile(path, 5);
await f.write("X", 11);
} finally {
await f.close();
}
assert.deepEqual(await readFile(path), Buffer.from("alpha\0\0\0\0\0\0X"));
}));
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/truncate-a-file/.
// Package truncatefile sets the size of a file.
package truncatefile
import "os"
// TruncateFile sets the size of the existing file at path to length bytes.
// os.Truncate cuts the bytes after length, or adds zero bytes up to length,
// and it does not make a missing file. The error is a *fs.PathError, for
// example with fs.ErrNotExist, syscall.EISDIR, or syscall.EINVAL for a length
// under 0.
func TruncateFile(path string, length int64) error {
return os.Truncate(path, length)
}
truncate_file_test.go 99 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/truncate-a-file/.
package truncatefile
import (
"errors"
"io"
"io/fs"
"os"
"path/filepath"
"syscall"
"testing"
)
func must(t *testing.T, err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}
func check(t *testing.T, path, want string) {
t.Helper()
got, err := os.ReadFile(path)
must(t, err)
if string(got) != want {
t.Errorf("got %q, want %q", got, want)
}
}
func TestCases(t *testing.T) {
cases := []struct {
name, path string
length int64
before, after string
}{
{"shrink", "a.txt", 5, "alpha beta\n", "alpha"},
{"extend", "a.txt", 8, "alpha", "alpha\x00\x00\x00"},
{"same-length", "a.txt", 6, "alpha\n", "alpha\n"},
{"to-zero", "a.txt", 0, "alpha\n", ""},
{"empty-file", "a.txt", 3, "", "\x00\x00\x00"},
{"name-with-spaces", "my notes.txt", 2, "alpha\n", "al"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
path := filepath.Join(t.TempDir(), c.path)
must(t, os.WriteFile(path, []byte(c.before), 0o644))
must(t, TruncateFile(path, c.length))
check(t, path, c.after)
})
}
}
func TestErrors(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "a.txt")
if err := TruncateFile(path, 0); !errors.Is(err, fs.ErrNotExist) {
t.Errorf("missing: got %v", err)
}
if _, err := os.Lstat(path); !errors.Is(err, fs.ErrNotExist) {
t.Errorf("the call made a file: %v", err)
}
must(t, os.Mkdir(filepath.Join(dir, "dir"), 0o755))
if err := TruncateFile(filepath.Join(dir, "dir"), 0); !errors.Is(err, syscall.EISDIR) {
t.Errorf("directory: got %v", err)
}
must(t, os.WriteFile(path, []byte("alpha\n"), 0o644))
if err := TruncateFile(path, -1); !errors.Is(err, syscall.EINVAL) {
t.Errorf("negative: got %v", err)
}
check(t, path, "alpha\n")
}
func TestOpenInAppendMode(t *testing.T) {
path := filepath.Join(t.TempDir(), "app.log")
must(t, os.WriteFile(path, []byte("alpha beta\n"), 0o644))
log, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0)
must(t, err)
must(t, TruncateFile(path, 0))
_, err = log.WriteString("new\n")
must(t, err)
must(t, log.Close())
check(t, path, "new\n")
}
func TestOpenAfterTheNewEnd(t *testing.T) {
path := filepath.Join(t.TempDir(), "data.bin")
must(t, os.WriteFile(path, []byte("alpha beta\n"), 0o644))
f, err := os.OpenFile(path, os.O_WRONLY, 0)
must(t, err)
_, err = f.Seek(0, io.SeekEnd)
must(t, err)
must(t, TruncateFile(path, 5))
_, err = f.WriteString("X")
must(t, err)
must(t, f.Close())
check(t, path, "alpha\x00\x00\x00\x00\x00\x00X")
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/truncate-a-file/.
use std::fs::OpenOptions;
use std::io;
use std::path::Path;
/// Sets the size of the existing file at `path` to `length` bytes.
///
/// The file is opened for writing with no `create`, so a missing file gives
/// an error of kind `NotFound`. `File::set_len` cuts the bytes after
/// `length`, or adds zero bytes up to `length`. `length` is a `u64`, so it
/// cannot be under 0.
pub fn truncate_file(path: &Path, length: u64) -> io::Result<()> {
OpenOptions::new().write(true).open(path)?.set_len(length)
}
tests/truncate_file_test.rs 73 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/truncate-a-file/.
use std::fs::{self, OpenOptions};
use std::io::{ErrorKind, Seek, SeekFrom, Write};
use std::path::PathBuf;
use algo_truncate_a_file::truncate_file;
/// Returns a new, empty directory for one test.
fn new_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("truncate-file-{}-{name}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn cases() {
for (name, rel, length, before, after) in [
("shrink", "a.txt", 5, "alpha beta\n", "alpha"),
("extend", "a.txt", 8, "alpha", "alpha\0\0\0"),
("same-length", "a.txt", 6, "alpha\n", "alpha\n"),
("to-zero", "a.txt", 0, "alpha\n", ""),
("empty-file", "a.txt", 3, "", "\0\0\0"),
("name-with-spaces", "my notes.txt", 2, "alpha\n", "al"),
] {
let dir = new_dir(name);
let path = dir.join(rel);
fs::write(&path, before).unwrap();
truncate_file(&path, length).unwrap();
assert_eq!(fs::read(&path).unwrap(), after.as_bytes(), "{name}");
fs::remove_dir_all(&dir).unwrap();
}
}
#[test]
fn errors() {
let dir = new_dir("errors");
let path = dir.join("a.txt");
assert_eq!(truncate_file(&path, 0).unwrap_err().kind(), ErrorKind::NotFound);
assert!(fs::symlink_metadata(&path).is_err());
fs::create_dir(dir.join("dir")).unwrap();
assert_eq!(truncate_file(&dir.join("dir"), 0).unwrap_err().kind(), ErrorKind::IsADirectory);
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn open_in_append_mode() {
let dir = new_dir("append");
let path = dir.join("app.log");
fs::write(&path, "alpha beta\n").unwrap();
let mut log = OpenOptions::new().append(true).open(&path).unwrap();
truncate_file(&path, 0).unwrap();
log.write_all(b"new\n").unwrap();
drop(log);
assert_eq!(fs::read_to_string(&path).unwrap(), "new\n");
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn open_after_the_new_end() {
let dir = new_dir("hole");
let path = dir.join("data.bin");
fs::write(&path, "alpha beta\n").unwrap();
let mut f = OpenOptions::new().write(true).open(&path).unwrap();
f.seek(SeekFrom::End(0)).unwrap();
truncate_file(&path, 5).unwrap();
f.write_all(b"X").unwrap();
drop(f);
assert_eq!(fs::read(&path).unwrap(), b"alpha\0\0\0\0\0\0X");
fs::remove_dir_all(&dir).unwrap();
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/truncate-a-file/.
# truncate_file PATH LENGTH
# Sets the size of the existing file at PATH to LENGTH bytes. POSIX has no
# truncate utility, so the function uses dd: with an empty input, seek= and
# no conv=notrunc, dd sets the size of the output file to the offset after
# the seek. That cuts the bytes after LENGTH, or adds zero bytes up to
# LENGTH. dd makes a missing file, so the function returns status 1 first
# for a missing file, for a directory and for a LENGTH that is not a
# whole number.
truncate_file() {
if [[ ! $2 =~ ^[0-9]+$ ]]; then
printf 'truncate_file: %s: invalid length\n' "$2" >&2
return 1
fi
if [[ -d $1 ]]; then
printf 'truncate_file: %s: is a directory\n' "$1" >&2
return 1
fi
if [[ ! -e $1 ]]; then
printf 'truncate_file: %s: no such file\n' "$1" >&2
return 1
fi
dd if=/dev/null of="$1" bs=1 seek="$2" 2>/dev/null
}
test_truncate_file.bats 70 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/truncate-a-file/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/truncate_file.sh"
dir=$BATS_TEST_TMPDIR
}
# hex FILE prints the bytes of FILE as hex digits.
hex() { od -An -v -tx1 "$1" | tr -d ' \n'; }
@test "shrink" {
printf 'alpha beta\n' >"$dir/a.txt"
truncate_file "$dir/a.txt" 5
[ "$(cat "$dir/a.txt")" = alpha ]
[ "$(hex "$dir/a.txt")" = 616c706861 ]
}
@test "extend" {
printf 'alpha' >"$dir/a.txt"
truncate_file "$dir/a.txt" 8
[ "$(hex "$dir/a.txt")" = 616c706861000000 ]
}
@test "same length" {
printf 'alpha\n' >"$dir/a.txt"
truncate_file "$dir/a.txt" 6
[ "$(hex "$dir/a.txt")" = 616c7068610a ]
}
@test "to zero" {
printf 'alpha\n' >"$dir/a.txt"
truncate_file "$dir/a.txt" 0
[ ! -s "$dir/a.txt" ]
}
@test "empty file" {
: >"$dir/a.txt"
truncate_file "$dir/a.txt" 3
[ "$(hex "$dir/a.txt")" = 000000 ]
}
@test "name with spaces" {
printf 'alpha\n' >"$dir/my notes.txt"
truncate_file "$dir/my notes.txt" 2
[ "$(cat "$dir/my notes.txt")" = al ]
}
@test "errors" {
run -1 truncate_file "$dir/a.txt" 0
[ ! -e "$dir/a.txt" ]
mkdir "$dir/dir"
run -1 truncate_file "$dir/dir" 0
printf 'alpha\n' >"$dir/a.txt"
run -1 truncate_file "$dir/a.txt" -1
run -1 truncate_file "$dir/a.txt" 2x
[ "$(cat "$dir/a.txt")" = alpha ]
}
@test "open in append mode" {
printf 'alpha beta\n' >"$dir/app.log"
exec 3>>"$dir/app.log"
truncate_file "$dir/app.log" 0
printf 'new\n' >&3
exec 3>&-
[ "$(cat "$dir/app.log")" = new ]
}
References
- The Python Standard Library, os, Miscellaneous operating system interfaces, os.truncate
- The Python Standard Library, io, Core tools for working with streams, IOBase.truncate
- The Python Standard Library, Built-in Functions, open, mode
- Node.js documentation, File system, fsPromises.truncate(path[, len]), filehandle.truncate(len)
- Java SE 25 API, FileChannel, truncate(long)
- Java SE 25 API, RandomAccessFile, RandomAccessFile(String, String), setLength(long)
- .NET API reference, FileStream.SetLength(Int64) Method, Remarks
- .NET API reference, FileMode Enum, Fields (Append, Truncate)
- Go standard library, package os, func Truncate
- The Rust Standard Library, std::fs::File, set_len
- The Open Group Base Specifications Issue 8 (POSIX.1-2024), truncate, DESCRIPTION, ERRORS
- The Open Group Base Specifications Issue 8 (POSIX.1-2024), ftruncate, DESCRIPTION
- The Open Group Base Specifications Issue 8 (POSIX.1-2024), dd, OPERANDS (seek=)
- Linux manual page, truncate(2), DESCRIPTION
- cppreference, std::filesystem::resize_file, Description
- Windows API reference, SetEndOfFile function (fileapi.h), Remarks
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag VHM159 Edit this page History Report an error Markdown