Programming Search⌘K

Taskintro

Delete a file

Also called remove a file, unlink a file, delete a file if it exists, rm.

Delete the file at a path and tell whether a file was there, with no error for a missing file but an error for a directory and for each other failure, such as a permission error.

Task

Delete the file at a path. Return true if a file was there and the call deleted it, and false if no file was there. A missing file is not an error: the result is the same, because no file is at the path after the call. A missing directory in the path, or a path through a regular file such as a.txt/b.txt, also gives false.

Report each other error, and do not take it for a missing file. For example, if the directory does not let the program write to it, the file stays, and the call must say so. A directory at the path is an error, also an empty one: this task deletes files, not directories.

If the path names a symbolic link, delete the link, not its target. A broken link is an entry too, so the call deletes it and returns true.

Do not check first and then delete. The answer of the check can be old when the program acts on it, and a check that gives false for a broken link leaves the link there. Delete, then look at the error. See the pitfalls.

SQL, regular expressions, HTML and CSS do not apply, because they do not delete files.

Solutions

On Unix, a file has no call that deletes the data. The unlink call removes one name of the file from its directory: "When the file's link count becomes 0 and no process has a reference to the file via an open file descriptor or a memory mapping (see mmap () ), the space occupied by the file shall be freed and the file shall no longer be accessible." So the right to delete a file comes from the directory, not from the file: unlink fails with EACCES when "write permission is denied on the directory containing the directory entry to be removed".

Each solution calls the delete function of its language. If the error is ENOENT (no such entry) or ENOTDIR (a part of the path is not a directory), the solution returns false. Each other error goes to the caller. Some delete functions also delete an empty directory, so those solutions look at the entry first, with no link followed, and report an error for a directory.

  • Python. os.remove(path). "If path is a directory, an OSError is raised." A missing file gives FileNotFoundError, and a path through a file gives NotADirectoryError, so the code looks at errno for both.
  • JavaScript and TypeScript (Node.js). fsPromises.unlink(path), which "Asynchronously removes a file or symbolic link." On an error with code ENOENT or ENOTDIR, the code returns false.
  • Java. Files.delete(path) also deletes a directory: "If the file is a directory then the directory must be empty." So the code reads the attributes with LinkOption.NOFOLLOW_LINKS first and throws a FileSystemException for a directory. For a link, "the symbolic link itself, not the final target of the link, is deleted." Java has no exception type for ENOTDIR, so the code looks for the nearest parent that is there, as in Check whether a file exists. Files.deleteIfExists returns a boolean too, but it also deletes an empty directory.
  • C#. File.Delete(path) gives no result: "If the file to be deleted does not exist, no exception is thrown." So the code calls File.GetAttributes first. That call does not follow a link, and it throws FileNotFoundException or DirectoryNotFoundException when no entry is there. For a directory, File.Delete throws UnauthorizedAccessException, and the code throws an IOException first.
  • Go. os.Remove "removes the named file or (empty) directory." So the code calls os.Lstat first and returns an error for a directory. Then os.Remove. errors.Is(err, fs.ErrNotExist) or errors.Is(err, syscall.ENOTDIR) gives false.
  • Rust. std::fs::remove_file(path). "This function currently corresponds to the unlink function on Unix." An error of kind ErrorKind::NotFound or ErrorKind::NotADirectory gives Ok(false).
  • C. POSIX unlink(path). It returns 1, 0, or -1 with errno for an error. The code does not use ISO C remove: "If path names a directory, remove ( path ) shall be equivalent to rmdir ( path )."
  • C++. std::filesystem::remove deletes "The file or empty directory identified by the path p", and it returns "true if the file was deleted, false if it did not exist." So the code calls std::filesystem::symlink_status first and gives std::errc::is_a_directory for a directory. The function returns std::expected<bool, std::error_code> (C++23).
  • Bash. rm -- "$path", with standard input from /dev/null. -- stops options, so a name such as -n is a file name. rm asks before it deletes a read-only file when standard input is a terminal: "If the -f option is not specified, and either the permissions of file do not permit writing and the standard input is a terminal or the -i option is specified, rm shall write a prompt to the standard error and read a line from the standard input." The code does not use -f, because it hides a missing file. If rm fails, the function looks at what is at the path, as in Check whether a file exists.

A program for people can move a file to the trash, and not delete it. There is no portable call for that. Java has Desktop.moveToTrash (since Java 9), which "Moves the specified file to the trash", and which throws UnsupportedOperationException on a platform with no trash. In .NET, Microsoft.VisualBasic.FileIO.FileSystem.DeleteFile takes a RecycleOption, for the Windows Recycle Bin. Linux desktops use the freedesktop.org Trash specification: "By complying with this Specification, various Trash implementations will be able to work with the same devices and use the same Trash storage."

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl. Each test makes the file in a new temporary directory, calls the function, and checks the result and that no entry is at the path after the call.

  • delete and missing: a file with text gives true, and a name that is not there gives false.
  • empty-file: an empty file is a file; its size does not matter.
  • missing-parent: no-such-dir/a.txt gives false, not an error.
  • name-with-spaces and non-ascii-name: my notes.txt and café 日本.txt. A shell solution must quote the name.
  • Errors, in cases/errors.jsonl: an empty directory at the path gives an error, and the directory stays.

The native tests also check that a path through a regular file gives false; that a link to a file, a link to a directory and a broken link are deleted, and their targets stay; that a read-only file is deleted; that a file in a directory with mode 500 gives a permission error and stays (skipped for root, because root can write to each directory); and that an open file is deleted while the open stream can still read it.

On Windows, an open file is not the same. os.remove says: "On Windows, attempting to remove a file that is in use causes an exception to be raised; on Unix, the directory entry is removed but the storage allocated to the file is not made available until the original file is no longer in use." The Windows DeleteFile function can delete an open file only if each other handle allows it ("FILE_SHARE_DELETE must have been specified when other handles were opened"), and then "the file deletion does not occur until the last handle to the file is closed". Also on Windows, a read-only file cannot be deleted: "If the file is a read-only file, the function fails with ERROR_ACCESS_DENIED ." The native tests run on Unix only.

Pitfalls

  • A check before the delete. os.path.exists follows links, so it gives False for a broken link, and the code does not delete the link:

This code runs but gives a wrong answer on purpose.

import os
import tempfile

with tempfile.TemporaryDirectory() as dir:
    link = os.path.join(dir, "report.txt")
    os.symlink("old-report.txt", link)  # a link to a file that is gone
    if os.path.exists(link):  # False for a broken link
        os.remove(link)
    print(os.listdir(dir))
Output
['report.txt']

The name report.txt is not free, so a new file with that name goes through the link to old-report.txt. A check also has a race: another program can delete the file between the check and the delete, and then the delete fails. Call the delete function and look at the error.

  • A delete function that also deletes a directory. Go os.Remove, Java Files.delete, C remove and C++ std::filesystem::remove delete an empty directory with no error. If the path names a directory by mistake, the directory is gone:

This code runs but gives a wrong answer on purpose.

package main

import (
	"fmt"
	"os"
	"path/filepath"
)

func main() {
	dir, _ := os.MkdirTemp("", "remove")
	defer os.RemoveAll(dir)
	path := filepath.Join(dir, "cache") // the program thinks this is a file
	os.Mkdir(path, 0o755)
	fmt.Println(os.Remove(path))
	_, err := os.Stat(path)
	fmt.Println(os.IsNotExist(err))
}
Output
<nil>
true
  • An error that is hidden. rm -f and C# File.Delete give no error for a missing file. "-f Do not prompt for confirmation. Do not write diagnostic messages or modify the exit status in the case of no file operands, or in the case of operands that do not exist." A typo in the name then deletes nothing, and the program does not know:

This code runs but gives a wrong answer on purpose.

dir=$(mktemp -d)
printf 'alpha\n' >"$dir/report.txt"
rm -f "$dir/reprot.txt"  # a typo in the name
echo "rm -f gives $?"
ls "$dir"
rm -r "$dir"
Output
rm -f gives 0
report.txt

The same is true for code that catches each error and takes it for a missing file. Rust says: "This function will only ever return an error of kind NotFound if the given path does not exist. Note that the inverse is not true".

  • The space comes back only at the close. On Unix, a delete removes the name, but a program that has the file open can still read it, and the disk space is free only when the last program closes the file. A large log file that a server keeps open takes its space after the delete:
import os
import tempfile

with tempfile.TemporaryDirectory() as dir:
    path = os.path.join(dir, "big.log")
    with open(path, "w") as f:
        f.write("alpha\n")
    with open(path) as f:
        os.remove(path)
        print("name there:", os.path.exists(path))
        print("links to the data:", os.fstat(f.fileno()).st_nlink)
        print("data:", f.read(), end="")
Output
name there: False
links to the data: 0
data: alpha

The Linux manual says: "If the name was the last link to a file but any processes still have the file open, the file will remain in existence until the last file descriptor referring to it is closed." To give back the space of a log that is open, truncate the file, or make the program close it.

  • A read-only file is not safe from a delete. On Unix, the mode of the file does not decide; the mode of the directory does:
import os
import tempfile

with tempfile.TemporaryDirectory() as dir:
    path = os.path.join(dir, "keep.txt")
    with open(path, "w") as f:
        f.write("alpha\n")
    os.chmod(path, 0o444)  # read-only, but the directory lets us write to it
    os.remove(path)
    print("deleted:", not os.path.exists(path))
Output
deleted: True

To keep a file safe, take the write permission away from its directory. On Windows it is the other way: DeleteFile fails for a read-only file.

Code

The build runs the native tests of each language in a pinned toolchain.

delete_file.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/delete-a-file/.

import errno
import os


def delete_file(path: str | os.PathLike) -> bool:
    """Deletes the file at path. Gives True if a file was there, False if not.

    os.remove does not delete a directory, and it deletes a symbolic link,
    not its target. Each error other than "no such entry" comes out as an
    OSError, so a permission error is not taken for a missing file.
    """
    try:
        os.remove(path)
    except OSError as err:
        if err.errno in (errno.ENOENT, errno.ENOTDIR):
            return False
        raise
    return True
test_delete_file.py 96 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/delete-a-file/.

import os
from pathlib import Path

import pytest

from delete_file import delete_file

# name: (path, content before the call or None, result)
CASES = {
    "delete": ("a.txt", "alpha\n", True),
    "missing": ("a.txt", None, False),
    "empty-file": ("a.txt", "", True),
    "missing-parent": ("no-such-dir/a.txt", None, False),
    "name-with-spaces": ("my notes.txt", "alpha\n", True),
    "non-ascii-name": ("café 日本.txt", "alpha\n", True),
}


@pytest.mark.parametrize("name", CASES)
def test_cases(tmp_path: Path, name: str) -> None:
    rel, content, want = CASES[name]
    path = tmp_path / rel
    if content is not None:
        path.write_text(content, encoding="utf-8")
    assert delete_file(path) is want
    assert not os.path.lexists(path)


def test_through_a_file(tmp_path: Path) -> None:
    (tmp_path / "a.txt").write_text("alpha\n")
    assert delete_file(tmp_path / "a.txt" / "b.txt") is False
    assert (tmp_path / "a.txt").exists()


def test_directory(tmp_path: Path) -> None:
    (tmp_path / "dir").mkdir()
    with pytest.raises(OSError):
        delete_file(tmp_path / "dir")
    assert (tmp_path / "dir").is_dir()


def test_link_to_a_file(tmp_path: Path) -> None:
    (tmp_path / "a.txt").write_text("alpha\n")
    os.symlink("a.txt", tmp_path / "link")
    assert delete_file(tmp_path / "link") is True
    assert not os.path.lexists(tmp_path / "link")
    assert (tmp_path / "a.txt").read_text() == "alpha\n"


def test_link_to_a_directory(tmp_path: Path) -> None:
    (tmp_path / "dir").mkdir()
    os.symlink("dir", tmp_path / "link")
    assert delete_file(tmp_path / "link") is True
    assert not os.path.lexists(tmp_path / "link")
    assert (tmp_path / "dir").is_dir()


def test_broken_link(tmp_path: Path) -> None:
    os.symlink("missing.txt", tmp_path / "link")
    assert delete_file(tmp_path / "link") is True
    assert not os.path.lexists(tmp_path / "link")


def test_read_only_file(tmp_path: Path) -> None:
    path = tmp_path / "a.txt"
    path.write_text("alpha\n")
    path.chmod(0o444)
    assert delete_file(path) is True
    assert not path.exists()


@pytest.mark.skipif(os.geteuid() == 0, reason="root can write to each directory")
def test_directory_with_no_write_permission(tmp_path: Path) -> None:
    locked = tmp_path / "locked"
    locked.mkdir()
    path = locked / "a.txt"
    path.write_text("alpha\n")
    locked.chmod(0o500)
    try:
        with pytest.raises(PermissionError):
            delete_file(path)
        assert path.exists()
    finally:
        locked.chmod(0o700)


def test_open_file(tmp_path: Path) -> None:
    path = tmp_path / "a.txt"
    path.write_text("alpha\n")
    with open(path) as f:
        assert delete_file(path) is True
        assert not path.exists()
        assert f.read() == "alpha\n"  # the data stays until the close
delete_file.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/delete-a-file/.
// since: C++23 (std::expected)

#include "delete_file.hpp"

namespace fs = std::filesystem;

std::expected<bool, std::error_code> delete_file(const fs::path& path) {
    std::error_code ec;
    // fs::remove also deletes an empty directory, so look at the entry first,
    // with no link followed.
    const fs::file_status st = fs::symlink_status(path, ec);
    if (st.type() == fs::file_type::not_found) return false;
    if (ec) return std::unexpected(ec);
    if (st.type() == fs::file_type::directory) {
        return std::unexpected(std::make_error_code(std::errc::is_a_directory));
    }
    const bool removed = fs::remove(path, ec);  // false if another program deleted it first
    if (ec == std::errc::no_such_file_or_directory || ec == std::errc::not_a_directory) return false;
    if (ec) return std::unexpected(ec);
    return removed;
}
delete_file.hpp 15 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/delete-a-file/.
// since: C++23 (std::expected)

#pragma once

#include <expected>
#include <filesystem>
#include <system_error>

// Deletes the file at path. Gives true if a file was there and false if not.
// A directory gives std::errc::is_a_directory and stays. A symbolic link is
// deleted, not its target. Each other error, for example a permission error,
// gives its error code.
std::expected<bool, std::error_code> delete_file(const std::filesystem::path& path);
test_delete_file.cpp 104 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/delete-a-file/.

#include <cstdio>
#include <filesystem>
#include <fstream>
#include <iterator>
#include <string>
#include <system_error>

#include <unistd.h>

#include "delete_file.hpp"

namespace fs = std::filesystem;

namespace {

const fs::path dir = "delete_file_tree";
int failures = 0;

void touch(const fs::path& p, const std::string& text) {
    std::ofstream(p, std::ios::binary) << text;
}

bool lexists(const fs::path& p) {
    std::error_code ec;
    return fs::exists(fs::symlink_status(p, ec));
}

void check(const char* name, const fs::path& p, bool want) {
    auto got = delete_file(p);
    if (!got || *got != want || lexists(p)) {
        std::fprintf(stderr, "%s: %s\n", name, got ? (*got ? "true" : "false") : got.error().message().c_str());
        ++failures;
    }
}

void expect(bool ok, const char* what) {
    if (!ok) {
        std::fprintf(stderr, "%s\n", what);
        ++failures;
    }
}

}  // namespace

int main() {
    fs::remove_all(dir);
    fs::create_directory(dir);

    // The cases of cases/basic.jsonl and cases/edge.jsonl.
    touch(dir / "a.txt", "alpha\n");
    check("delete", dir / "a.txt", true);
    check("missing", dir / "a.txt", false);
    touch(dir / "a.txt", "");
    check("empty-file", dir / "a.txt", true);
    check("missing-parent", dir / "no-such-dir" / "a.txt", false);
    touch(dir / "my notes.txt", "alpha\n");
    check("name-with-spaces", dir / "my notes.txt", true);
    touch(dir / "café 日本.txt", "alpha\n");
    check("non-ascii-name", dir / "café 日本.txt", true);

    touch(dir / "a.txt", "alpha\n");
    check("through-a-file", dir / "a.txt" / "b.txt", false);

    fs::create_directory(dir / "dir");
    auto d = delete_file(dir / "dir");
    expect(!d && d.error() == std::errc::is_a_directory && fs::is_directory(dir / "dir"),
           "directory: no is_a_directory error");

    fs::create_symlink("a.txt", dir / "to-file");
    fs::create_directory_symlink("dir", dir / "to-dir");
    fs::create_symlink("missing.txt", dir / "broken");
    check("to-file", dir / "to-file", true);
    check("to-dir", dir / "to-dir", true);
    check("broken", dir / "broken", true);
    expect(fs::is_regular_file(dir / "a.txt") && fs::is_directory(dir / "dir"), "links: a target is gone");

    fs::permissions(dir / "a.txt", fs::perms::owner_read | fs::perms::group_read | fs::perms::others_read);
    check("read-only", dir / "a.txt", true);

    if (geteuid() != 0) {
        fs::create_directory(dir / "locked");
        touch(dir / "locked" / "a.txt", "alpha\n");
        fs::permissions(dir / "locked", fs::perms::owner_read | fs::perms::owner_exec);
        auto r = delete_file(dir / "locked" / "a.txt");
        expect(!r && r.error() == std::errc::permission_denied && fs::exists(dir / "locked" / "a.txt"),
               "locked: no permission error");
        fs::permissions(dir / "locked", fs::perms::owner_all);
    }

    touch(dir / "open.txt", "alpha\n");
    {
        std::ifstream in(dir / "open.txt", std::ios::binary);
        check("open", dir / "open.txt", true);
        std::string data{std::istreambuf_iterator<char>(in), {}};
        expect(data == "alpha\n", "open: cannot read the data");
    }

    fs::remove_all(dir);
    if (failures == 0) std::puts("ok");
    return failures == 0 ? 0 : 1;
}
DeleteFile.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/delete-a-file/.

import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.nio.file.FileSystemException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;

public final class DeleteFile {
  private DeleteFile() {}

  /**
   * Deletes the file at path. Gives true if a file was there, false if not.
   *
   * <p>Files.delete also deletes an empty directory, so the code looks at the entry first, with
   * no link followed, and does not delete a directory. A symbolic link is deleted, not its target.
   * Each error other than "no such entry" comes out as an IOException.
   */
  public static boolean delete(Path path) throws IOException {
    BasicFileAttributes attrs;
    try {
      attrs = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
    } catch (NoSuchFileException e) {
      return false;
    } catch (AccessDeniedException e) {
      throw e;
    } catch (FileSystemException e) {
      // Java has no exception type for ENOTDIR. A path through a regular file
      // has no entry, so look for the nearest parent that is there.
      if (throughAFile(path)) {
        return false;
      }
      throw e;
    }
    if (attrs.isDirectory()) {
      throw new FileSystemException(path.toString(), null, "Is a directory");
    }
    try {
      Files.delete(path);
    } catch (NoSuchFileException e) {
      return false; // another program deleted it first
    }
    return true;
  }

  private static boolean throughAFile(Path path) {
    for (Path p = path.getParent(); p != null; p = p.getParent()) {
      if (Files.exists(p)) {
        return !Files.isDirectory(p);
      }
    }
    return false;
  }
}
DeleteFileTest.java 115 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/delete-a-file/.

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 static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeFalse;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.AccessDeniedException;
import java.nio.file.FileSystemException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermissions;
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 DeleteFileTest {
  @TempDir Path dir;

  private boolean lexists(Path p) {
    return Files.exists(p, LinkOption.NOFOLLOW_LINKS);
  }

  @ParameterizedTest(name = "{0}")
  @CsvSource(
      delimiter = '|',
      nullValues = "NULL",
      emptyValue = "EMPTY",
      value = {
        "delete | a.txt | alpha | true",
        "missing | a.txt | NULL | false",
        "empty-file | a.txt | EMPTY | true",
        "missing-parent | no-such-dir/a.txt | NULL | false",
        "name-with-spaces | my notes.txt | alpha | true",
        "non-ascii-name | café 日本.txt | alpha | true",
      })
  void cases(String name, String rel, String content, boolean want) throws IOException {
    Path path = dir.resolve(rel);
    if (content != null) {
      Files.writeString(path, "EMPTY".equals(content) ? "" : content + "\n");
    }
    assertEquals(want, DeleteFile.delete(path));
    assertFalse(lexists(path));
  }

  @Test
  void throughAFile() throws IOException {
    Files.writeString(dir.resolve("a.txt"), "alpha\n");
    assertFalse(DeleteFile.delete(dir.resolve("a.txt").resolve("b.txt")));
    assertTrue(Files.exists(dir.resolve("a.txt")));
  }

  @Test
  void directory() throws IOException {
    Files.createDirectory(dir.resolve("dir"));
    assertThrows(FileSystemException.class, () -> DeleteFile.delete(dir.resolve("dir")));
    assertTrue(Files.isDirectory(dir.resolve("dir")));
  }

  @Test
  void links() throws IOException {
    Files.writeString(dir.resolve("a.txt"), "alpha\n");
    Files.createDirectory(dir.resolve("dir"));
    Files.createSymbolicLink(dir.resolve("to-file"), Path.of("a.txt"));
    Files.createSymbolicLink(dir.resolve("to-dir"), Path.of("dir"));
    Files.createSymbolicLink(dir.resolve("broken"), Path.of("missing.txt"));
    for (String link : new String[] {"to-file", "to-dir", "broken"}) {
      assertTrue(DeleteFile.delete(dir.resolve(link)), link);
      assertFalse(lexists(dir.resolve(link)), link);
    }
    assertEquals("alpha\n", Files.readString(dir.resolve("a.txt")));
    assertTrue(Files.isDirectory(dir.resolve("dir")));
  }

  @Test
  void readOnlyFile() throws IOException {
    Path path = dir.resolve("a.txt");
    Files.writeString(path, "alpha\n");
    Files.setPosixFilePermissions(path, PosixFilePermissions.fromString("r--r--r--"));
    assertTrue(DeleteFile.delete(path));
    assertFalse(lexists(path));
  }

  @Test
  void directoryWithNoWritePermission() throws IOException {
    assumeFalse("root".equals(System.getProperty("user.name")));
    Path locked = Files.createDirectory(dir.resolve("locked"));
    Path path = Files.writeString(locked.resolve("a.txt"), "alpha\n");
    Files.setPosixFilePermissions(locked, PosixFilePermissions.fromString("r-x------"));
    try {
      assertThrows(AccessDeniedException.class, () -> DeleteFile.delete(path));
      assertTrue(Files.exists(path));
    } finally {
      Files.setPosixFilePermissions(locked, PosixFilePermissions.fromString("rwx------"));
    }
  }

  @Test
  void openFile() throws IOException {
    Path path = Files.writeString(dir.resolve("a.txt"), "alpha\n");
    try (InputStream in = Files.newInputStream(path)) {
      assertTrue(DeleteFile.delete(path));
      assertFalse(lexists(path));
      // On Unix the data stays until the close.
      assertEquals("alpha\n", new String(in.readAllBytes(), StandardCharsets.UTF_8));
    }
  }
}
delete_file.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/delete-a-file/.

// unlink is in POSIX, not in ISO C. ISO C remove also deletes an empty
// directory, so it is not used.
#define _POSIX_C_SOURCE 200809L

#include "delete_file.h"

#include <errno.h>
#include <unistd.h>

int delete_file(const char *path) {
    if (unlink(path) == 0) return 1;
    if (errno == ENOENT || errno == ENOTDIR) return 0;
    return -1;
}
delete_file.h 13 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/delete-a-file/.

#ifndef DELETE_FILE_H
#define DELETE_FILE_H

// delete_file deletes the file at path with unlink. It returns 1 if a file was
// there, 0 if not (ENOENT, or ENOTDIR for a path through a regular file), and
// -1 with errno from unlink on each other error, for example EACCES. unlink
// does not delete a directory, and it deletes a symbolic link, not its target.
int delete_file(const char *path);

#endif
test_delete_file.c 114 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/delete-a-file/.

// symlink, lstat and geteuid are in POSIX.1-2008, not in ISO C.
#define _POSIX_C_SOURCE 200809L

#include "delete_file.h"

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

static const char *dir = "delete_file_tree";
static int failures = 0;

static const char *at(const char *name) {
    static char path[256];
    snprintf(path, sizeof path, "%s/%s", dir, name);
    return path;
}

static void touch(const char *name, const char *text) {
    FILE *f = fopen(at(name), "w");
    if (f == NULL || fputs(text, f) < 0 || fclose(f) != 0) exit(2);
}

static int lexists(const char *path) {
    struct stat st;
    return lstat(path, &st) == 0;
}

static void check(const char *name, int got, int want, const char *path) {
    if (got != want || lexists(path)) {
        fprintf(stderr, "%s: delete_file = %d, want %d, entry there: %d\n", name, got, want,
                lexists(path));
        failures++;
    }
}

int main(void) {
    if (system("rm -rf delete_file_tree") != 0 || mkdir(dir, 0755) != 0) return 2;

    // The cases of cases/basic.jsonl and cases/edge.jsonl.
    touch("a.txt", "alpha\n");
    check("delete", delete_file(at("a.txt")), 1, at("a.txt"));
    check("missing", delete_file(at("a.txt")), 0, at("a.txt"));
    touch("a.txt", "");
    check("empty-file", delete_file(at("a.txt")), 1, at("a.txt"));
    check("missing-parent", delete_file(at("no-such-dir/a.txt")), 0, at("no-such-dir/a.txt"));
    touch("my notes.txt", "alpha\n");
    check("name-with-spaces", delete_file(at("my notes.txt")), 1, at("my notes.txt"));
    touch("café 日本.txt", "alpha\n");
    check("non-ascii-name", delete_file(at("café 日本.txt")), 1, at("café 日本.txt"));

    // A path through a regular file gives ENOTDIR, and no entry is there.
    touch("a.txt", "alpha\n");
    check("through-a-file", delete_file(at("a.txt/b.txt")), 0, at("a.txt/b.txt"));

    // A directory is an error, and it stays.
    if (mkdir(at("dir"), 0755) != 0) return 2;
    if (delete_file(at("dir")) != -1 || !lexists(at("dir"))) {
        fprintf(stderr, "directory: no error\n");
        failures++;
    }

    // A link is deleted, not its target.
    if (symlink("a.txt", at("to-file")) != 0 || symlink("dir", at("to-dir")) != 0 ||
        symlink("missing.txt", at("broken")) != 0)
        return 2;
    check("to-file", delete_file(at("to-file")), 1, at("to-file"));
    check("to-dir", delete_file(at("to-dir")), 1, at("to-dir"));
    check("broken", delete_file(at("broken")), 1, at("broken"));
    if (!lexists(at("a.txt")) || !lexists(at("dir"))) {
        fprintf(stderr, "links: a target is gone\n");
        failures++;
    }

    // A read-only file is deleted: the permissions of the directory decide.
    if (chmod(at("a.txt"), 0444) != 0) return 2;
    check("read-only", delete_file(at("a.txt")), 1, at("a.txt"));

    // A file in a directory with no write permission gives EACCES and stays.
    if (geteuid() != 0) {
        if (mkdir(at("locked"), 0755) != 0) return 2;
        touch("locked/a.txt", "alpha\n");
        if (chmod(at("locked"), 0500) != 0) return 2;
        static char locked_file[256];
        snprintf(locked_file, sizeof locked_file, "%s/locked/a.txt", dir);
        if (delete_file(locked_file) != -1 || errno != EACCES || !lexists(locked_file)) {
            fprintf(stderr, "locked: no EACCES\n");
            failures++;
        }
        if (chmod(at("locked"), 0700) != 0) return 2;
    }

    // An open file is deleted, and the open stream can still read it.
    touch("open.txt", "alpha\n");
    FILE *f = fopen(at("open.txt"), "r");
    if (f == NULL) return 2;
    check("open", delete_file(at("open.txt")), 1, at("open.txt"));
    char buf[16] = {0};
    if (fgets(buf, sizeof buf, f) == NULL || strcmp(buf, "alpha\n") != 0) {
        fprintf(stderr, "open: cannot read the data\n");
        failures++;
    }
    fclose(f);

    if (system("rm -rf delete_file_tree") != 0) return 2;
    if (failures == 0) printf("ok\n");
    return failures == 0 ? 0 : 1;
}
DeleteFile.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/delete-a-file/.

public static class DeleteFile
{
    /// <summary>
    /// Deletes the file at path. Gives true if a file was there and false if not.
    /// File.Delete gives no error and no result for a missing file, so the code
    /// looks at the entry first. File.GetAttributes does not follow a symbolic
    /// link, so a link is deleted, not its target. A directory is an error.
    /// Each other error, for example UnauthorizedAccessException, goes to the caller.
    /// </summary>
    public static bool Delete(string path)
    {
        FileAttributes attrs;
        try
        {
            attrs = File.GetAttributes(path);
        }
        catch (FileNotFoundException)
        {
            return false;
        }
        catch (DirectoryNotFoundException)
        {
            return false; // a missing directory, or a path through a regular file
        }
        if (attrs.HasFlag(FileAttributes.Directory) && !attrs.HasFlag(FileAttributes.ReparsePoint))
        {
            throw new IOException($"{path} is a directory");
        }
        File.Delete(path);
        return true;
    }
}
DeleteFileTests.cs 117 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/delete-a-file/.

using Xunit;

public sealed class DeleteFileTests : IDisposable
{
    private readonly string dir = Directory.CreateTempSubdirectory("delete-file-").FullName;

    public void Dispose() => Directory.Delete(dir, recursive: true);

    private static bool LExists(string path) => Path.Exists(path) || new FileInfo(path).LinkTarget != null;

    // name, path, content before the call or null, result
    public static TheoryData<string, string, string?, bool> Cases => new()
    {
        { "delete", "a.txt", "alpha\n", true },
        { "missing", "a.txt", null, false },
        { "empty-file", "a.txt", "", true },
        { "missing-parent", "no-such-dir/a.txt", null, false },
        { "name-with-spaces", "my notes.txt", "alpha\n", true },
        { "non-ascii-name", "café 日本.txt", "alpha\n", true },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Deletes(string name, string rel, string? content, bool want)
    {
        string path = Path.Combine(dir, rel);
        if (content != null)
        {
            File.WriteAllText(path, content);
        }
        Assert.True(want == DeleteFile.Delete(path), name);
        Assert.False(LExists(path), name);
    }

    [Fact]
    public void ThroughAFile()
    {
        File.WriteAllText(Path.Combine(dir, "a.txt"), "alpha\n");
        Assert.False(DeleteFile.Delete(Path.Combine(dir, "a.txt", "b.txt")));
        Assert.True(File.Exists(Path.Combine(dir, "a.txt")));
    }

    [Fact]
    public void Directory_()
    {
        string sub = Directory.CreateDirectory(Path.Combine(dir, "dir")).FullName;
        Assert.Throws<IOException>(() => DeleteFile.Delete(sub));
        Assert.True(Directory.Exists(sub));
    }

    [Fact]
    public void Links()
    {
        File.WriteAllText(Path.Combine(dir, "a.txt"), "alpha\n");
        Directory.CreateDirectory(Path.Combine(dir, "dir"));
        File.CreateSymbolicLink(Path.Combine(dir, "to-file"), "a.txt");
        Directory.CreateSymbolicLink(Path.Combine(dir, "to-dir"), "dir");
        File.CreateSymbolicLink(Path.Combine(dir, "broken"), "missing.txt");
        foreach (string link in new[] { "to-file", "to-dir", "broken" })
        {
            Assert.True(DeleteFile.Delete(Path.Combine(dir, link)), link);
            Assert.False(LExists(Path.Combine(dir, link)), link);
        }
        Assert.Equal("alpha\n", File.ReadAllText(Path.Combine(dir, "a.txt")));
        Assert.True(Directory.Exists(Path.Combine(dir, "dir")));
    }

    [Fact]
    public void ReadOnlyFile()
    {
        string path = Path.Combine(dir, "a.txt");
        File.WriteAllText(path, "alpha\n");
        File.SetAttributes(path, FileAttributes.ReadOnly);
        Assert.True(DeleteFile.Delete(path));
        Assert.False(LExists(path));
    }

    [Fact]
    public void DirectoryWithNoWritePermission()
    {
        if (OperatingSystem.IsWindows() || Environment.IsPrivilegedProcess)
        {
            return; // root can write to each directory
        }
        string locked = Directory.CreateDirectory(Path.Combine(dir, "locked")).FullName;
        string path = Path.Combine(locked, "a.txt");
        File.WriteAllText(path, "alpha\n");
        File.SetUnixFileMode(locked, UnixFileMode.UserRead | UnixFileMode.UserExecute);
        try
        {
            Assert.Throws<UnauthorizedAccessException>(() => DeleteFile.Delete(path));
            Assert.True(File.Exists(path));
        }
        finally
        {
            File.SetUnixFileMode(locked, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
        }
    }

    [Fact]
    public void OpenFile()
    {
        if (OperatingSystem.IsWindows())
        {
            return; // on Windows a file that is open with no FileShare.Delete cannot be deleted
        }
        string path = Path.Combine(dir, "a.txt");
        File.WriteAllText(path, "alpha\n");
        using var reader = new StreamReader(path);
        Assert.True(DeleteFile.Delete(path));
        Assert.False(LExists(path));
        Assert.Equal("alpha\n", reader.ReadToEnd()); // on Unix the data stays until the close
    }
}
deleteFile.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/delete-a-file/.

import { unlink } from "node:fs/promises";

/**
 * Deletes the file at path. Gives true if a file was there, false if not.
 * unlink does not delete a directory, and it deletes a symbolic link, not its
 * target. Each error other than "no such entry" is thrown, so a permission
 * error is not taken for a missing file.
 */
export async function deleteFile(path) {
  try {
    await unlink(path);
  } catch (err) {
    if (err.code === "ENOENT" || err.code === "ENOTDIR") {
      return false;
    }
    throw err;
  }
  return true;
}
deleteFile.test.js 115 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/delete-a-file/.

import { test } from "node:test";
import assert from "node:assert/strict";
import { existsSync, lstatSync } from "node:fs";
import { chmod, mkdir, mkdtemp, open, readFile, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { deleteFile } from "./deleteFile.js";

async function withDir(fn) {
  const dir = await mkdtemp(join(tmpdir(), "delete-file-"));
  try {
    await fn(dir);
  } finally {
    await rm(dir, { recursive: true, force: true });
  }
}

function lexists(path) {
  try {
    lstatSync(path);
    return true;
  } catch {
    return false;
  }
}

// name: [path, content before the call or null, result]
const cases = {
  delete: ["a.txt", "alpha\n", true],
  missing: ["a.txt", null, false],
  "empty-file": ["a.txt", "", true],
  "missing-parent": ["no-such-dir/a.txt", null, false],
  "name-with-spaces": ["my notes.txt", "alpha\n", true],
  "non-ascii-name": ["café 日本.txt", "alpha\n", true],
};

for (const [name, [rel, content, want]] of Object.entries(cases)) {
  test(name, () =>
    withDir(async (dir) => {
      const path = join(dir, rel);
      if (content !== null) await writeFile(path, content);
      assert.equal(await deleteFile(path), want);
      assert.equal(lexists(path), false);
    }));
}

test("through a file", () =>
  withDir(async (dir) => {
    await writeFile(join(dir, "a.txt"), "alpha\n");
    assert.equal(await deleteFile(join(dir, "a.txt", "b.txt")), false);
    assert.equal(existsSync(join(dir, "a.txt")), true);
  }));

test("directory", () =>
  withDir(async (dir) => {
    await mkdir(join(dir, "dir"));
    await assert.rejects(deleteFile(join(dir, "dir")));
    assert.equal(lstatSync(join(dir, "dir")).isDirectory(), true);
  }));

test("links", () =>
  withDir(async (dir) => {
    await writeFile(join(dir, "a.txt"), "alpha\n");
    await mkdir(join(dir, "dir"));
    await symlink("a.txt", join(dir, "to-file"));
    await symlink("dir", join(dir, "to-dir"));
    await symlink("missing.txt", join(dir, "broken"));
    for (const link of ["to-file", "to-dir", "broken"]) {
      assert.equal(await deleteFile(join(dir, link)), true);
      assert.equal(lexists(join(dir, link)), false);
    }
    assert.equal(await readFile(join(dir, "a.txt"), "utf8"), "alpha\n");
    assert.equal(lstatSync(join(dir, "dir")).isDirectory(), true);
  }));

test("read-only file", () =>
  withDir(async (dir) => {
    const path = join(dir, "a.txt");
    await writeFile(path, "alpha\n");
    await chmod(path, 0o444);
    assert.equal(await deleteFile(path), true);
    assert.equal(lexists(path), false);
  }));

test("directory with no write permission", { skip: process.getuid?.() === 0 }, () =>
  withDir(async (dir) => {
    const locked = join(dir, "locked");
    await mkdir(locked);
    const path = join(locked, "a.txt");
    await writeFile(path, "alpha\n");
    await chmod(locked, 0o500);
    try {
      await assert.rejects(deleteFile(path), { code: "EACCES" });
      assert.equal(existsSync(path), true);
    } finally {
      await chmod(locked, 0o700);
    }
  }));

test("open file", () =>
  withDir(async (dir) => {
    const path = join(dir, "a.txt");
    await writeFile(path, "alpha\n");
    const f = await open(path);
    try {
      assert.equal(await deleteFile(path), true);
      assert.equal(lexists(path), false);
      assert.equal(await f.readFile("utf8"), "alpha\n"); // the data stays until the close
    } finally {
      await f.close();
    }
  }));
deleteFile.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/delete-a-file/.

import { unlink } from "node:fs/promises";

/**
 * Deletes the file at path. Gives true if a file was there, false if not.
 * unlink does not delete a directory, and it deletes a symbolic link, not its
 * target. Each error other than "no such entry" is thrown, so a permission
 * error is not taken for a missing file.
 */
export async function deleteFile(path: string): Promise<boolean> {
  try {
    await unlink(path);
  } catch (err) {
    const code = (err as NodeJS.ErrnoException).code;
    if (code === "ENOENT" || code === "ENOTDIR") {
      return false;
    }
    throw err;
  }
  return true;
}
deleteFile.test.ts 115 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/delete-a-file/.

import { test } from "node:test";
import assert from "node:assert/strict";
import { existsSync, lstatSync } from "node:fs";
import { chmod, mkdir, mkdtemp, open, readFile, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { deleteFile } from "./deleteFile.ts";

async function withDir(fn: (dir: string) => Promise<void>): Promise<void> {
  const dir = await mkdtemp(join(tmpdir(), "delete-file-"));
  try {
    await fn(dir);
  } finally {
    await rm(dir, { recursive: true, force: true });
  }
}

function lexists(path: string): boolean {
  try {
    lstatSync(path);
    return true;
  } catch {
    return false;
  }
}

// name: [path, content before the call or null, result]
const cases: Record<string, [string, string | null, boolean]> = {
  delete: ["a.txt", "alpha\n", true],
  missing: ["a.txt", null, false],
  "empty-file": ["a.txt", "", true],
  "missing-parent": ["no-such-dir/a.txt", null, false],
  "name-with-spaces": ["my notes.txt", "alpha\n", true],
  "non-ascii-name": ["café 日本.txt", "alpha\n", true],
};

for (const [name, [rel, content, want]] of Object.entries(cases)) {
  test(name, () =>
    withDir(async (dir) => {
      const path = join(dir, rel);
      if (content !== null) await writeFile(path, content);
      assert.equal(await deleteFile(path), want);
      assert.equal(lexists(path), false);
    }));
}

test("through a file", () =>
  withDir(async (dir) => {
    await writeFile(join(dir, "a.txt"), "alpha\n");
    assert.equal(await deleteFile(join(dir, "a.txt", "b.txt")), false);
    assert.equal(existsSync(join(dir, "a.txt")), true);
  }));

test("directory", () =>
  withDir(async (dir) => {
    await mkdir(join(dir, "dir"));
    await assert.rejects(deleteFile(join(dir, "dir")));
    assert.equal(lstatSync(join(dir, "dir")).isDirectory(), true);
  }));

test("links", () =>
  withDir(async (dir) => {
    await writeFile(join(dir, "a.txt"), "alpha\n");
    await mkdir(join(dir, "dir"));
    await symlink("a.txt", join(dir, "to-file"));
    await symlink("dir", join(dir, "to-dir"));
    await symlink("missing.txt", join(dir, "broken"));
    for (const link of ["to-file", "to-dir", "broken"]) {
      assert.equal(await deleteFile(join(dir, link)), true);
      assert.equal(lexists(join(dir, link)), false);
    }
    assert.equal(await readFile(join(dir, "a.txt"), "utf8"), "alpha\n");
    assert.equal(lstatSync(join(dir, "dir")).isDirectory(), true);
  }));

test("read-only file", () =>
  withDir(async (dir) => {
    const path = join(dir, "a.txt");
    await writeFile(path, "alpha\n");
    await chmod(path, 0o444);
    assert.equal(await deleteFile(path), true);
    assert.equal(lexists(path), false);
  }));

test("directory with no write permission", { skip: process.getuid?.() === 0 }, () =>
  withDir(async (dir) => {
    const locked = join(dir, "locked");
    await mkdir(locked);
    const path = join(locked, "a.txt");
    await writeFile(path, "alpha\n");
    await chmod(locked, 0o500);
    try {
      await assert.rejects(deleteFile(path), { code: "EACCES" });
      assert.equal(existsSync(path), true);
    } finally {
      await chmod(locked, 0o700);
    }
  }));

test("open file", () =>
  withDir(async (dir) => {
    const path = join(dir, "a.txt");
    await writeFile(path, "alpha\n");
    const f = await open(path);
    try {
      assert.equal(await deleteFile(path), true);
      assert.equal(lexists(path), false);
      assert.equal(await f.readFile("utf8"), "alpha\n"); // the data stays until the close
    } finally {
      await f.close();
    }
  }));
delete_file.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/delete-a-file/.

// Package deletefile deletes a file and tells whether a file was there.
package deletefile

import (
	"errors"
	"io/fs"
	"os"
	"syscall"
)

// ErrIsADirectory is the error for a path that names a directory.
var ErrIsADirectory = errors.New("is a directory")

// gone reports whether err means that no entry is at the path: ENOENT, or
// ENOTDIR for a path through a regular file.
func gone(err error) bool {
	return errors.Is(err, fs.ErrNotExist) || errors.Is(err, syscall.ENOTDIR)
}

// DeleteFile deletes the file at path. It gives true if a file was there and
// false if not. os.Remove also deletes an empty directory, so the code looks
// at the entry first, with os.Lstat, and does not delete a directory. A
// symbolic link is deleted, not its target. Each other error goes to the
// caller.
func DeleteFile(path string) (bool, error) {
	info, err := os.Lstat(path)
	if err != nil {
		if gone(err) {
			return false, nil
		}
		return false, err
	}
	if info.IsDir() {
		return false, &fs.PathError{Op: "delete", Path: path, Err: ErrIsADirectory}
	}
	if err := os.Remove(path); err != nil {
		if gone(err) {
			return false, nil // another program deleted it first
		}
		return false, err
	}
	return true, nil
}
delete_file_test.go 139 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/delete-a-file/.

package deletefile

import (
	"errors"
	"io"
	"io/fs"
	"os"
	"path/filepath"
	"testing"
)

func must(t *testing.T, err error) {
	t.Helper()
	if err != nil {
		t.Fatal(err)
	}
}

func lexists(path string) bool {
	_, err := os.Lstat(path)
	return err == nil
}

func TestCases(t *testing.T) {
	cases := []struct {
		name, path string
		content    *string
		want       bool
	}{
		{"delete", "a.txt", ptr("alpha\n"), true},
		{"missing", "a.txt", nil, false},
		{"empty-file", "a.txt", ptr(""), true},
		{"missing-parent", "no-such-dir/a.txt", nil, false},
		{"name-with-spaces", "my notes.txt", ptr("alpha\n"), true},
		{"non-ascii-name", "café 日本.txt", ptr("alpha\n"), true},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			path := filepath.Join(t.TempDir(), c.path)
			if c.content != nil {
				must(t, os.WriteFile(path, []byte(*c.content), 0o644))
			}
			got, err := DeleteFile(path)
			if err != nil || got != c.want {
				t.Fatalf("DeleteFile = %v, %v; want %v", got, err, c.want)
			}
			if lexists(path) {
				t.Fatal("the file is still there")
			}
		})
	}
}

func ptr(s string) *string { return &s }

func TestThroughAFile(t *testing.T) {
	dir := t.TempDir()
	must(t, os.WriteFile(filepath.Join(dir, "a.txt"), []byte("alpha\n"), 0o644))
	got, err := DeleteFile(filepath.Join(dir, "a.txt", "b.txt"))
	if got || err != nil {
		t.Fatalf("got %v, %v", got, err)
	}
}

func TestDirectory(t *testing.T) {
	dir := filepath.Join(t.TempDir(), "dir")
	must(t, os.Mkdir(dir, 0o755))
	if _, err := DeleteFile(dir); !errors.Is(err, ErrIsADirectory) {
		t.Fatalf("err = %v", err)
	}
	if !lexists(dir) {
		t.Fatal("the directory is gone")
	}
}

func TestLinks(t *testing.T) {
	dir := t.TempDir()
	must(t, os.WriteFile(filepath.Join(dir, "a.txt"), []byte("alpha\n"), 0o644))
	must(t, os.Mkdir(filepath.Join(dir, "dir"), 0o755))
	must(t, os.Symlink("a.txt", filepath.Join(dir, "to-file")))
	must(t, os.Symlink("dir", filepath.Join(dir, "to-dir")))
	must(t, os.Symlink("missing.txt", filepath.Join(dir, "broken")))
	for _, link := range []string{"to-file", "to-dir", "broken"} {
		got, err := DeleteFile(filepath.Join(dir, link))
		if !got || err != nil || lexists(filepath.Join(dir, link)) {
			t.Fatalf("%s: got %v, %v", link, got, err)
		}
	}
	if b, _ := os.ReadFile(filepath.Join(dir, "a.txt")); string(b) != "alpha\n" {
		t.Fatal("the target is changed")
	}
	if !lexists(filepath.Join(dir, "dir")) {
		t.Fatal("the target directory is gone")
	}
}

func TestReadOnlyFile(t *testing.T) {
	path := filepath.Join(t.TempDir(), "a.txt")
	must(t, os.WriteFile(path, []byte("alpha\n"), 0o444))
	if got, err := DeleteFile(path); !got || err != nil || lexists(path) {
		t.Fatalf("got %v, %v", got, err)
	}
}

func TestDirectoryWithNoWritePermission(t *testing.T) {
	if os.Geteuid() == 0 {
		t.Skip("root can write to each directory")
	}
	locked := filepath.Join(t.TempDir(), "locked")
	must(t, os.Mkdir(locked, 0o755))
	path := filepath.Join(locked, "a.txt")
	must(t, os.WriteFile(path, []byte("alpha\n"), 0o644))
	must(t, os.Chmod(locked, 0o500))
	defer os.Chmod(locked, 0o700)
	if _, err := DeleteFile(path); !errors.Is(err, fs.ErrPermission) {
		t.Fatalf("err = %v", err)
	}
	if !lexists(path) {
		t.Fatal("the file is gone")
	}
}

func TestOpenFile(t *testing.T) {
	path := filepath.Join(t.TempDir(), "a.txt")
	must(t, os.WriteFile(path, []byte("alpha\n"), 0o644))
	f, err := os.Open(path)
	must(t, err)
	defer f.Close()
	if got, err := DeleteFile(path); !got || err != nil || lexists(path) {
		t.Fatalf("got %v, %v", got, err)
	}
	b, err := io.ReadAll(f) // on Unix the data stays until the close
	if err != nil || string(b) != "alpha\n" {
		t.Fatalf("read %q, %v", b, err)
	}
}
delete_file.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/delete-a-file/.

use std::fs;
use std::io::{self, ErrorKind};
use std::path::Path;

/// Deletes the file at `path`. Gives `Ok(true)` if a file was there and
/// `Ok(false)` if not. `fs::remove_file` does not delete a directory, and it
/// deletes a symbolic link, not its target. Each error other than "no such
/// entry" goes to the caller.
pub fn delete_file(path: impl AsRef<Path>) -> io::Result<bool> {
    match fs::remove_file(path) {
        Ok(()) => Ok(true),
        Err(e) if matches!(e.kind(), ErrorKind::NotFound | ErrorKind::NotADirectory) => Ok(false),
        Err(e) => Err(e),
    }
}
tests/delete_file_test.rs 122 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/delete-a-file/.

use std::fs;
use std::io::{ErrorKind, Read};
use std::os::unix::fs::{symlink, PermissionsExt};
use std::path::{Path, PathBuf};

use algo_delete_a_file::delete_file;

/// Returns a new, empty directory for one test.
fn new_dir(name: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("delete-file-{}-{name}", std::process::id()));
    let _ = fs::remove_dir_all(&dir);
    fs::create_dir_all(&dir).unwrap();
    dir
}

fn lexists(path: &Path) -> bool {
    fs::symlink_metadata(path).is_ok()
}

#[test]
fn cases() {
    for (name, rel, content, want) in [
        ("delete", "a.txt", Some("alpha\n"), true),
        ("missing", "a.txt", None, false),
        ("empty-file", "a.txt", Some(""), true),
        ("missing-parent", "no-such-dir/a.txt", None, false),
        ("name-with-spaces", "my notes.txt", Some("alpha\n"), true),
        ("non-ascii-name", "café 日本.txt", Some("alpha\n"), true),
    ] {
        let dir = new_dir(name);
        let path = dir.join(rel);
        if let Some(c) = content {
            fs::write(&path, c).unwrap();
        }
        assert_eq!(delete_file(&path).unwrap(), want, "{name}");
        assert!(!lexists(&path), "{name}");
        fs::remove_dir_all(&dir).unwrap();
    }
}

#[test]
fn through_a_file() {
    let dir = new_dir("through");
    fs::write(dir.join("a.txt"), "alpha\n").unwrap();
    assert!(!delete_file(dir.join("a.txt/b.txt")).unwrap());
    assert!(dir.join("a.txt").exists());
    fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn directory() {
    let dir = new_dir("directory");
    fs::create_dir(dir.join("dir")).unwrap();
    assert!(delete_file(dir.join("dir")).is_err());
    assert!(dir.join("dir").is_dir());
    fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn links() {
    let dir = new_dir("links");
    fs::write(dir.join("a.txt"), "alpha\n").unwrap();
    fs::create_dir(dir.join("dir")).unwrap();
    symlink("a.txt", dir.join("to-file")).unwrap();
    symlink("dir", dir.join("to-dir")).unwrap();
    symlink("missing.txt", dir.join("broken")).unwrap();
    for link in ["to-file", "to-dir", "broken"] {
        assert!(delete_file(dir.join(link)).unwrap(), "{link}");
        assert!(!lexists(&dir.join(link)), "{link}");
    }
    assert_eq!(fs::read_to_string(dir.join("a.txt")).unwrap(), "alpha\n");
    assert!(dir.join("dir").is_dir());
    fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn read_only_file() {
    let dir = new_dir("read-only");
    let path = dir.join("a.txt");
    fs::write(&path, "alpha\n").unwrap();
    fs::set_permissions(&path, fs::Permissions::from_mode(0o444)).unwrap();
    assert!(delete_file(&path).unwrap());
    assert!(!lexists(&path));
    fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn directory_with_no_write_permission() {
    let dir = new_dir("locked");
    let locked = dir.join("locked");
    fs::create_dir(&locked).unwrap();
    let path = locked.join("a.txt");
    fs::write(&path, "alpha\n").unwrap();
    fs::set_permissions(&locked, fs::Permissions::from_mode(0o500)).unwrap();
    // Root can write to each directory, so there is no error for root.
    let probe = locked.join("probe");
    let root = fs::write(&probe, "").is_ok();
    if !root {
        let err = delete_file(&path).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::PermissionDenied);
        assert!(path.exists());
    }
    fs::set_permissions(&locked, fs::Permissions::from_mode(0o700)).unwrap();
    fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn open_file() {
    let dir = new_dir("open");
    let path = dir.join("a.txt");
    fs::write(&path, "alpha\n").unwrap();
    let mut f = fs::File::open(&path).unwrap();
    assert!(delete_file(&path).unwrap());
    assert!(!lexists(&path));
    let mut s = String::new();
    f.read_to_string(&mut s).unwrap(); // on Unix the data stays until the close
    assert_eq!(s, "alpha\n");
    fs::remove_dir_all(&dir).unwrap();
}
delete_file.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/delete-a-file/.

# delete_file NAME PATH
# Deletes the file at PATH and stores true in the variable NAME if a file was
# there, false if not. rm with no -r does not delete a directory, and it
# deletes a symbolic link, not its target. Standard input comes from
# /dev/null, because rm asks before it deletes a read-only file when standard
# input is a terminal. -f is not used, because it hides a missing file. If rm
# fails and the entry is still there, the function writes the error of rm and
# returns status 1. If no entry is there, it looks at the nearest parent that
# is there: if that parent is a directory that the shell cannot search, the
# function returns status 1, because it cannot tell whether a file is there.
delete_file() {
  local _err _parent
  if _err=$(rm -- "$2" 2>&1 </dev/null); then
    printf -v "$1" '%s' true
    return 0
  fi
  if [[ -e $2 || -L $2 ]]; then
    printf '%s\n' "$_err" >&2
    return 1
  fi
  _parent=$2
  while [[ $_parent != / && $_parent != . ]]; do
    _parent=$(dirname -- "$_parent")
    [[ -e $_parent || -L $_parent ]] && break
  done
  if [[ -d $_parent && ! -x $_parent ]]; then
    printf 'delete_file: %s: cannot search the directory %s\n' "$2" "$_parent" >&2
    return 1
  fi
  printf -v "$1" '%s' false
}
test_delete_file.bats 76 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/delete-a-file/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/delete_file.sh"
  dir=$BATS_TEST_TMPDIR
}

lexists() { [[ -e $1 || -L $1 ]]; }

check() { # check PATH WANT
  local got
  delete_file got "$1"
  [ "$got" = "$2" ]
  ! lexists "$1"
}

@test "delete" { printf 'alpha\n' >"$dir/a.txt"; check "$dir/a.txt" true; }
@test "missing" { check "$dir/a.txt" false; }
@test "empty file" { : >"$dir/a.txt"; check "$dir/a.txt" true; }
@test "missing parent" { check "$dir/no-such-dir/a.txt" false; }
@test "name with spaces" { printf 'alpha\n' >"$dir/my notes.txt"; check "$dir/my notes.txt" true; }
@test "non-ASCII name" { printf 'alpha\n' >"$dir/café 日本.txt"; check "$dir/café 日本.txt" true; }
@test "name that starts with a dash" { printf 'alpha\n' >"$dir/-n"; cd "$dir"; check -n true; }

@test "through a file" {
  printf 'alpha\n' >"$dir/a.txt"
  check "$dir/a.txt/b.txt" false
  [ -f "$dir/a.txt" ]
}

@test "directory" {
  mkdir "$dir/dir"
  run -1 delete_file got "$dir/dir"
  [ -d "$dir/dir" ]
}

@test "links" {
  printf 'alpha\n' >"$dir/a.txt"
  mkdir "$dir/dir"
  ln -s a.txt "$dir/to-file"
  ln -s dir "$dir/to-dir"
  ln -s missing.txt "$dir/broken"
  check "$dir/to-file" true
  check "$dir/to-dir" true
  check "$dir/broken" true
  [ "$(cat "$dir/a.txt")" = alpha ]
  [ -d "$dir/dir" ]
}

@test "read-only file" {
  printf 'alpha\n' >"$dir/a.txt"
  chmod 444 "$dir/a.txt"
  check "$dir/a.txt" true
}

@test "directory with no write permission" {
  [ "$(id -u)" -ne 0 ] || skip "root can write to each directory"
  mkdir "$dir/locked"
  printf 'alpha\n' >"$dir/locked/a.txt"
  chmod 500 "$dir/locked"
  run -1 delete_file got "$dir/locked/a.txt"
  chmod 700 "$dir/locked"
  [ -f "$dir/locked/a.txt" ]
}

@test "open file" {
  printf 'alpha\n' >"$dir/a.txt"
  exec 3<"$dir/a.txt"
  check "$dir/a.txt" true
  [ "$(cat <&3)" = alpha ] # on Unix the data stays until the close
  exec 3<&-
}

References

  1. The Python Standard Library, os, Miscellaneous operating system interfaces, os.remove, os.unlink
  2. Node.js documentation, File system, fsPromises.unlink(path), fs.unlink(path, callback)
  3. Java SE 25 API, Files, delete(Path), deleteIfExists(Path)
  4. Java SE 25 API, Desktop, moveToTrash(File)
  5. .NET API reference, File.Delete(String) Method, Remarks, Exceptions
  6. .NET API reference, FileSystem.DeleteFile Method, DeleteFile(String, UIOption, RecycleOption)
  7. Go standard library, package os, func Remove, func Lstat
  8. The Rust Standard Library, std::fs::remove_file, Platform-specific behavior, Errors
  9. The Open Group Base Specifications Issue 8 (POSIX.1-2024), unlink, unlinkat, DESCRIPTION, ERRORS
  10. The Open Group Base Specifications Issue 8 (POSIX.1-2024), remove, DESCRIPTION
  11. The Open Group Base Specifications Issue 8 (POSIX.1-2024), rm, DESCRIPTION, OPTIONS (-f)
  12. Linux manual page, unlink(2), DESCRIPTION, ERRORS (EISDIR)
  13. cppreference, std::filesystem::remove, std::filesystem::remove_all, Return value
  14. Windows API reference, DeleteFileW function (fileapi.h), Remarks
  15. freedesktop.org, Trash specification, Abstract

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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source