Taskintro
Get the size of a file
Also called file size, size of a file in bytes, length of a file, stat size, st_size.
Get the size in bytes of a regular file from the file system, with no read of its data, and know why it is not the count of characters or the space on the disk.
- Evidence
- Code in 10 languages
Task
Return the size in bytes of the regular file at path. The size comes from the file system, as the st_size field of stat gives it. POSIX defines that field: "For regular files, the file size in bytes. For symbolic links, the length in bytes of the pathname contained in the symbolic link." So the function must follow a symbolic link, and give the size of its target. The function does not read the data of the file, so a file of some gigabytes takes no more time than a small one.
Report an error when no file is at path, and when path is a directory. Most calls give a number for a directory, but that number is not the size of a file, and it is not the same on each file system. C++ says: "The result of attempting to determine the size of a directory (as well as any other file that is not a regular file or a symlink) is implementation-defined."
The size is a count of bytes. It is not a count of characters, and it is not the space that the file uses on the disk. The pitfalls show both.
SQL, regular expressions, HTML and CSS do not apply, because they do not get information about files.
Solutions
Each language has a call that gets the status of a file, and the size is one field of it. Some languages also have a call that gives only the size. Each solution gets the status one time, and uses it for the directory check and for the size, so that the two values come from the same file.
- Python.
os.stat(path).st_size.os.statdoes "the equivalent of a stat() system call on the given path", andst_sizeis the "Size of the file in bytes, if it is a regular file or a symbolic link." The code raisesIsADirectoryErrorfor a directory.os.path.getsize(path)is shorter: "Return the size, in bytes, of path . Raise OSError if the file does not exist or is inaccessible." But it gives a number for a directory. - JavaScript and TypeScript (Node.js).
(await fsPromises.stat(path)).size.stats.sizeis "The size of the file in bytes. If the underlying file system does not support getting the size of the file, this will be 0 ." The code throws an error with the codeEISDIRfor a directory. Usestat(path, { bigint: true })to get abigint. - Java.
Files.readAttributes(path, BasicFileAttributes.class).size().Files.size(path)"Returns the size of a file (in bytes)", but "The size of files that are not regular files is implementation specific and therefore unspecified." So the code reads the attributes, and throws aFileSystemExceptionfor a directory. The size is along. - C#.
new FileInfo(path).Length. It "Gets the size, in bytes, of the current file". It throwsFileNotFoundExceptionwhen "The file does not exist. -or- The Length property is called for a directory." So the code throws anIOExceptionfor a directory first, to keep the two errors apart. For a symbolic link,Lengthis the size of the link, not the size of the target. The native test shows this on macOS. So the code callsResolveLinkTarget(returnFinalTarget: true)first. - Go.
os.Stat(path)and thenfi.Size(), anint64. "Stat returns a FileInfo describing the named file. If there is an error, it will be of type *PathError ." The code returns a*fs.PathErrorwithsyscall.EISDIRfor a directory. For a file that is open,f.Stat()gives the sameFileInfo. - Rust.
fs::metadata(path)?.len(), au64. It "Returns the size of the file, in bytes, this metadata is for." The code returnsErrorKind::IsADirectoryfor a directory. - C. POSIX
stat(path, &st)and thenst.st_size, anoff_t. The function returns 0 or -1, and puts the size in an argument, because -1 is not a size. For a directory it setserrnotoEISDIR. ISO C has no call that gets the size of a file. The codefseek(f, 0, SEEK_END)and thenftell(f)is common, but it opens the file, andftellreturns along. - C++.
std::filesystem::file_size(path, ec). "For a regular file p , returns the size determined as if by reading the st_size member of the structure obtained by POSIX stat (symlinks are followed)." The code checks for a directory first, because the result for a directory is implementation-defined. The function is in a namespace, because a call withstd::filesystem::patharguments also findsstd::filesystem::file_size. - Bash. POSIX has no
statutility, so the code useswc -c <"$path". The-coption will "Write to the standard output the number of bytes in each input file". The input comes from a redirection, and "If no input file operands are specified, no name shall be written". Some versions ofwcput spaces before the number, so the code removes them. On macOS and on Linux,wc -cgets the size of a regular file from the file system, with no read: the native test of a sparse file of 5 GiB takes less than one second. The function returns status 1 for a missing file and for a directory.
On Windows, the system call that gives the size of an open file is GetFileSizeEx. It "Retrieves the size of the specified file" through a handle.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl. Each test writes the file in a new temporary directory, and checks the size that the function returns.
text:alpha\nis 6 bytes.non-ascii-text:café\nis 5 characters, but 6 bytes in UTF-8.empty-file: the size is 0. That is a result, not an error.binary-data: the bytes00 0D 0A C3 BF 00. The size does not change in text mode: a NUL byte and a line end are bytes.crlf-line-ends:a\r\nb\r\nis 6 bytes, also on Windows.name-with-spacesandnon-ascii-name:my notes.txtandcafé 日本.txt. A shell solution must quote the names.- Errors, in
cases/errors.jsonl: a missing file gives not-found, and a directory gives is-a-directory.
The native tests also check that a symbolic link gives the size of its target (11, not the 5 bytes of the name a.txt); that a sparse file of 5368709120 bytes (5 GiB) gives that size, more than a 32-bit integer can hold; and that a file that a program has open gives the new size after the program flushes its data.
Pitfalls
- A size before the flush. A buffered stream keeps the data in memory until the buffer is full, or until a flush or a close. Until then, the file system does not have the data, and the size does not include it:
This code runs but gives a wrong answer on purpose.
import os
import tempfile
with tempfile.TemporaryDirectory() as dir:
path = os.path.join(dir, "app.log")
with open(path, "w") as log:
log.write("alpha\n")
print("size:", os.path.getsize(path)) # the data is still in the buffer
size: 0
Call flush() first, to "Flush the write buffers of the stream if applicable." The C test shows the same with fputs and fflush. An *os.File in Go and a File in Rust have no buffer, so a write goes to the file system at once.
- A count of characters is not a size. The length of the text that a program reads is a count of characters after decoding, not a count of bytes:
This code runs but gives a wrong answer on purpose.
import os
import tempfile
with tempfile.TemporaryDirectory() as dir:
path = os.path.join(dir, "a.txt")
with open(path, "w", encoding="utf-8") as f:
f.write("café\n")
with open(path, encoding="utf-8") as f:
print("characters:", len(f.read()))
print("bytes:", os.path.getsize(path))
characters: 5
bytes: 6
The same is true for wc -m against wc -c. -m will "Write to the standard output the number of characters in each input file." Also, a read of all the data to count it is slow for a large file, and a program does not need it.
- The size is not the space on the disk. A file can have holes, parts that have no blocks on the disk and that read as zero bytes. Python says that
st_blocksis the "Number of 512-byte blocks allocated for file. This may be smaller than st_size /512 when the file has holes." A file system that compresses data can also use less space than the size. Java says: "The size may differ from the actual size on the file system due to compression, support for sparse files, or other reasons."
import os
import tempfile
with tempfile.TemporaryDirectory() as dir:
path = os.path.join(dir, "sparse.bin")
with open(path, "wb") as f:
f.truncate(1024**3) # 1 GiB, with no data written
st = os.stat(path)
print("size:", st.st_size)
print("allocated less than size:", st.st_blocks * 512 < st.st_size)
size: 1073741824
allocated less than size: True
To find the space on the disk, use st_blocks, or du. By default, du writes "the size of the file space allocated to" each file, not the size.
-
The size of a symbolic link.
lstat, and each call that does not follow links, gives the length of the target path, not the size of the target. In C#,FileInfo.Lengthdoes the same. -
A size that changes. The size is correct at the time of the call. Another program can write to the file, or truncate it, before the next step. To read a whole file, read until the end, and do not trust a buffer of the size that
statgave. Some files give a size of 0 although they have data. Node says that "If the underlying file system does not support getting the size of the file, this will be 0". -
A size in a 32-bit integer. A file can be larger than 2 GiB. Keep the size in a 64-bit type:
off_twith 64-bit file offsets,longin Java and C#,int64in Go,u64in Rust.
Related tasks
- Truncate a file
- Read a whole file
- Check whether a file exists
- Get the modification time of a file
- File metadata
- Sparse file
- Hard links and symbolic links
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/get-the-size-of-a-file/.
import errno
import os
import stat
def file_size(path: str | os.PathLike) -> int:
"""Returns the size in bytes of the regular file at path.
os.stat follows a symbolic link, so a link gives the size of its target.
A missing file raises FileNotFoundError. os.stat also gives a size for a
directory, but it is not the size of a file, so the code raises
IsADirectoryError.
"""
st = os.stat(path)
if stat.S_ISDIR(st.st_mode):
raise IsADirectoryError(errno.EISDIR, os.strerror(errno.EISDIR), os.fspath(path))
return st.st_size
test_file_size.py 61 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/get-the-size-of-a-file/.
import os
from pathlib import Path
import pytest
from file_size import file_size
# name: (path, content, size)
CASES = {
"text": ("a.txt", "alpha\n".encode(), 6),
"non-ascii-text": ("a.txt", "café\n".encode(), 6),
"empty-file": ("a.txt", b"", 0),
"binary-data": ("a.bin", b"\x00\r\n\xc3\xbf\x00", 6),
"crlf-line-ends": ("a.txt", b"a\r\nb\r\n", 6),
"name-with-spaces": ("my notes.txt", b"alpha\n", 6),
"non-ascii-name": ("café 日本.txt", b"alpha\n", 6),
}
@pytest.mark.parametrize("name", CASES)
def test_cases(tmp_path: Path, name: str) -> None:
rel, data, size = CASES[name]
path = tmp_path / rel
path.write_bytes(data)
assert file_size(path) == size
assert path.read_bytes() == data
def test_errors(tmp_path: Path) -> None:
with pytest.raises(FileNotFoundError):
file_size(tmp_path / "a.txt")
(tmp_path / "dir").mkdir()
with pytest.raises(IsADirectoryError):
file_size(tmp_path / "dir")
def test_symbolic_link(tmp_path: Path) -> None:
(tmp_path / "a.txt").write_bytes(b"alpha beta\n")
os.symlink("a.txt", tmp_path / "link")
assert file_size(tmp_path / "link") == 11
def test_sparse_file_of_5_gib(tmp_path: Path) -> None:
path = tmp_path / "sparse.bin"
path.write_bytes(b"")
os.truncate(path, 5 * 1024**3)
assert file_size(path) == 5368709120
def test_open_file_after_flush(tmp_path: Path) -> None:
path = tmp_path / "app.log"
with open(path, "wb") as f:
f.write(b"alpha\n")
f.flush()
assert file_size(path) == 6
f.write(b"beta\n")
f.flush()
assert file_size(path) == 11
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-size-of-a-file/.
#include "file_size.hpp"
namespace fs = std::filesystem;
std::uintmax_t files::file_size(const fs::path& path, std::error_code& ec) {
// fs::file_size reports an error for a directory, but the error code is
// not the same in each library, so the code checks for a directory first.
if (fs::is_directory(path, ec)) {
ec = std::make_error_code(std::errc::is_a_directory);
return static_cast<std::uintmax_t>(-1);
}
return fs::file_size(path, ec);
}
file_size.hpp 20 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-size-of-a-file/.
#pragma once
#include <cstdint>
#include <filesystem>
#include <system_error>
// Returns the size in bytes of the regular file at path, with
// std::filesystem::file_size. It follows a symbolic link. On an error it sets
// ec and returns static_cast<std::uintmax_t>(-1): for example
// std::errc::no_such_file_or_directory, or std::errc::is_a_directory for a
// directory. The function is in a namespace, because a call with
// std::filesystem::path arguments also finds std::filesystem::file_size.
namespace files {
std::uintmax_t file_size(const std::filesystem::path& path, std::error_code& ec);
} // namespace files
test_file_size.cpp 86 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-size-of-a-file/.
#include <cstdint>
#include <cstdio>
#include <filesystem>
#include <fstream>
#include <string>
#include <system_error>
#include "file_size.hpp"
namespace fs = std::filesystem;
using namespace std::string_literals;
namespace {
const fs::path dir = "file_size_tree";
int failures = 0;
void put(const fs::path& p, const std::string& text) { std::ofstream(p, std::ios::binary) << text; }
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 fs::path& path, const std::string& data) {
fresh();
put(dir / path, data);
std::error_code ec;
std::uintmax_t size = files::file_size(dir / path, ec);
expect(!ec && size == data.size(), name);
}
void test_errors() {
fresh();
std::error_code ec;
files::file_size(dir / "a.txt", ec);
expect(ec == std::errc::no_such_file_or_directory, "missing");
fs::create_directory(dir / "dir");
files::file_size(dir / "dir", ec);
expect(ec == std::errc::is_a_directory, "directory");
}
void test_link_sparse_open() {
fresh();
std::error_code ec;
put(dir / "a.txt", "alpha beta\n");
fs::create_symlink("a.txt", dir / "link");
expect(files::file_size(dir / "link", ec) == 11 && !ec, "link");
put(dir / "sparse.bin", "");
fs::resize_file(dir / "sparse.bin", std::uintmax_t{5} << 30);
expect(files::file_size(dir / "sparse.bin", ec) == 5368709120 && !ec, "sparse");
std::ofstream log(dir / "app.log", std::ios::binary);
log << "alpha\n" << std::flush;
expect(files::file_size(dir / "app.log", ec) == 6 && !ec, "open after flush");
}
} // namespace
int main() {
run_case("text", "a.txt", "alpha\n");
run_case("non-ascii-text", "a.txt", "caf\xc3\xa9\n");
run_case("empty-file", "a.txt", "");
run_case("binary-data", "a.bin", "\x00\r\n\xc3\xbf\x00"s);
run_case("crlf-line-ends", "a.txt", "a\r\nb\r\n");
run_case("name-with-spaces", "my notes.txt", "alpha\n");
run_case("non-ascii-name", fs::path(u8"café 日本.txt"), "alpha\n");
test_errors();
test_link_sparse_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/get-the-size-of-a-file/.
import java.io.IOException;
import java.nio.file.FileSystemException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
final class FileSize {
private FileSize() {}
/**
* Returns the size in bytes of the regular file at path. readAttributes follows a symbolic link,
* so a link gives the size of its target. A missing file gives NoSuchFileException. Files.size
* also gives a size for a directory, but it is not the size of a file, so the code throws a
* FileSystemException.
*/
static long size(Path path) throws IOException {
BasicFileAttributes a = Files.readAttributes(path, BasicFileAttributes.class);
if (a.isDirectory()) {
throw new FileSystemException(path.toString(), null, "Is a directory");
}
return a.size();
}
}
FileSizeTest.java 81 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-size-of-a-file/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
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 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 FileSizeTest {
@TempDir Path dir;
private static byte[] bytes(String s) {
return s.replace("EMPTY", "").replace("\\n", "\n").replace("\\r", "\r").getBytes(StandardCharsets.UTF_8);
}
@ParameterizedTest(name = "{0}")
@CsvSource({
"text, a.txt, alpha\\n, 6",
"non-ascii-text, a.txt, café\\n, 6",
"empty-file, a.txt, EMPTY, 0",
"crlf-line-ends, a.txt, a\\r\\nb\\r\\n, 6",
"name-with-spaces, my notes.txt, alpha\\n, 6",
"non-ascii-name, café 日本.txt, alpha\\n, 6",
})
void cases(String name, String rel, String data, long size) throws IOException {
Path path = dir.resolve(rel);
Files.write(path, bytes(data));
assertEquals(size, FileSize.size(path), name);
}
@Test
void binaryData() throws IOException {
Path path = dir.resolve("a.bin");
Files.write(path, new byte[] {0x00, 0x0d, 0x0a, (byte) 0xc3, (byte) 0xbf, 0x00});
assertEquals(6, FileSize.size(path));
}
@Test
void errors() throws IOException {
assertThrows(NoSuchFileException.class, () -> FileSize.size(dir.resolve("a.txt")));
Files.createDirectory(dir.resolve("dir"));
assertThrows(FileSystemException.class, () -> FileSize.size(dir.resolve("dir")));
}
@Test
void symbolicLink() throws IOException {
Files.writeString(dir.resolve("a.txt"), "alpha beta\n");
Files.createSymbolicLink(dir.resolve("link"), Path.of("a.txt"));
assertEquals(11, FileSize.size(dir.resolve("link")));
}
@Test
void sparseFileOf5GiB() throws IOException {
Path path = dir.resolve("sparse.bin");
try (RandomAccessFile f = new RandomAccessFile(path.toFile(), "rw")) {
f.setLength(5L * 1024 * 1024 * 1024);
}
assertEquals(5368709120L, FileSize.size(path));
}
@Test
void openFileAfterFlush() throws IOException {
Path path = dir.resolve("app.log");
try (OutputStream out = Files.newOutputStream(path)) {
out.write(bytes("alpha\\n"));
out.flush();
assertEquals(6, FileSize.size(path));
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-size-of-a-file/.
#define _POSIX_C_SOURCE 200809L
#include "file_size.h"
#include <errno.h>
#include <sys/stat.h>
int file_size(const char *path, off_t *size) {
struct stat st;
if (stat(path, &st) != 0) return -1;
if (S_ISDIR(st.st_mode)) {
errno = EISDIR;
return -1;
}
*size = st.st_size;
return 0;
}
file_size.h 15 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-size-of-a-file/.
#ifndef FILE_SIZE_H
#define FILE_SIZE_H
#include <sys/types.h>
// file_size stores the size in bytes of the regular file at path in *size.
// stat follows a symbolic link, so a link gives the size of its target. It
// returns 0, or -1 with errno: ENOENT for a missing file, and EISDIR for a
// directory, because the size of a directory is not the size of a file.
int file_size(const char *path, off_t *size);
#endif
test_file_size.c 97 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-size-of-a-file/.
#define _POSIX_C_SOURCE 200809L
#include "file_size.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 = "file_size_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 void expect(int ok, const char *what) {
if (!ok) {
fprintf(stderr, "%s\n", what);
failures++;
}
}
static void fresh(void) {
if (system("rm -rf file_size_tree") != 0 || mkdir(dir, 0755) != 0) exit(2);
}
static void run_case(const char *name, const char *path, const char *data, size_t n) {
char p[256];
off_t size = -1;
fresh();
put(path, data, n);
expect(file_size(at(p, path), &size) == 0 && size == (off_t)n, name);
}
static void test_errors(void) {
char p[256];
off_t size;
fresh();
errno = 0;
expect(file_size(at(p, "a.txt"), &size) == -1 && errno == ENOENT, "missing");
if (mkdir(at(p, "dir"), 0755) != 0) exit(2);
errno = 0;
expect(file_size(at(p, "dir"), &size) == -1 && errno == EISDIR, "directory");
}
static void test_link_sparse_open(void) {
char p[256], q[256];
off_t size = -1;
fresh();
put("a.txt", "alpha beta\n", 11);
expect(symlink("a.txt", at(p, "link")) == 0, "symlink");
expect(file_size(p, &size) == 0 && size == 11, "link");
int f = open(at(p, "sparse.bin"), O_WRONLY | O_CREAT | O_EXCL, 0644);
expect(f >= 0 && ftruncate(f, (off_t)5 << 30) == 0 && close(f) == 0, "make sparse");
expect(file_size(p, &size) == 0 && size == 5368709120, "sparse");
FILE *log = fopen(at(q, "app.log"), "w");
if (log == NULL) exit(2);
fputs("alpha\n", log);
expect(file_size(q, &size) == 0 && size == 0, "before fflush");
expect(fflush(log) == 0 && file_size(q, &size) == 0 && size == 6, "after fflush");
fclose(log);
}
int main(void) {
run_case("text", "a.txt", "alpha\n", 6);
run_case("non-ascii-text", "a.txt", "caf\xc3\xa9\n", 6);
run_case("empty-file", "a.txt", "", 0);
run_case("binary-data", "a.bin", "\x00\r\n\xc3\xbf\x00", 6);
run_case("crlf-line-ends", "a.txt", "a\r\nb\r\n", 6);
run_case("name-with-spaces", "my notes.txt", "alpha\n", 6);
run_case("non-ascii-name", "caf\xc3\xa9 \xe6\x97\xa5\xe6\x9c\xac.txt", "alpha\n", 6);
test_errors();
test_link_sparse_open();
if (system("rm -rf file_size_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/get-the-size-of-a-file/.
public static class FileSize
{
/// <summary>
/// Returns the size in bytes of the regular file at path. FileInfo.Length
/// gives FileNotFoundException for a missing file. For a directory it also
/// gives FileNotFoundException, so the code throws an IOException first.
/// For a symbolic link, FileInfo.Length is the size of the link itself, so
/// the code gets the FileInfo of the final target first.
/// </summary>
public static long Size(string path)
{
if (Directory.Exists(path))
{
throw new IOException($"Is a directory: '{path}'");
}
var info = new FileInfo(path);
if (info.LinkTarget != null)
{
info = (FileInfo?)info.ResolveLinkTarget(returnFinalTarget: true) ?? info;
}
return info.Length;
}
}
FileSizeTests.cs 73 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-size-of-a-file/.
using System.Text;
using Xunit;
public sealed class FileSizeTests : IDisposable
{
private readonly string dir = Directory.CreateTempSubdirectory("file-size-").FullName;
public void Dispose() => Directory.Delete(dir, recursive: true);
// name, path, content, size
public static TheoryData<string, string, string, long> Cases => new()
{
{ "text", "a.txt", "alpha\n", 6 },
{ "non-ascii-text", "a.txt", "café\n", 6 },
{ "empty-file", "a.txt", "", 0 },
{ "binary-data", "a.bin", "\0\r\nÿ\0", 6 },
{ "crlf-line-ends", "a.txt", "a\r\nb\r\n", 6 },
{ "name-with-spaces", "my notes.txt", "alpha\n", 6 },
{ "non-ascii-name", "café 日本.txt", "alpha\n", 6 },
};
[Theory]
[MemberData(nameof(Cases))]
public void Case(string name, string rel, string data, long size)
{
string path = Path.Combine(dir, rel);
File.WriteAllBytes(path, Encoding.UTF8.GetBytes(data));
Assert.True(size == FileSize.Size(path), name);
}
[Fact]
public void Errors()
{
Assert.Throws<FileNotFoundException>(() => FileSize.Size(Path.Combine(dir, "a.txt")));
Directory.CreateDirectory(Path.Combine(dir, "dir"));
var e = Assert.Throws<IOException>(() => FileSize.Size(Path.Combine(dir, "dir")));
Assert.Contains("Is a directory", e.Message);
}
[Fact]
public void SymbolicLink()
{
File.WriteAllText(Path.Combine(dir, "a.txt"), "alpha beta\n");
File.CreateSymbolicLink(Path.Combine(dir, "link"), "a.txt");
Assert.Equal(11, FileSize.Size(Path.Combine(dir, "link")));
// FileInfo.Length alone gives the size of the link: the 5 bytes of "a.txt".
Assert.Equal(5, new FileInfo(Path.Combine(dir, "link")).Length);
}
[Fact]
public void SparseFileOf5GiB()
{
string path = Path.Combine(dir, "sparse.bin");
using (var f = new FileStream(path, FileMode.CreateNew, FileAccess.Write))
{
f.SetLength(5L * 1024 * 1024 * 1024);
}
Assert.Equal(5368709120L, FileSize.Size(path));
}
[Fact]
public void OpenFileAfterFlush()
{
string path = Path.Combine(dir, "app.log");
using var f = new FileStream(path, FileMode.CreateNew, FileAccess.Write);
f.Write("alpha\n"u8);
f.Flush();
Assert.Equal(6, FileSize.Size(path));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-size-of-a-file/.
import { stat } from "node:fs/promises";
/**
* Returns the size in bytes of the regular file at path. stat follows a
* symbolic link, so a link gives the size of its target. A missing file
* gives an error with the code ENOENT. stat also gives a size for a
* directory, but it is not the size of a file, so the code throws an error
* with the code EISDIR.
*/
export async function fileSize(path) {
const st = await stat(path);
if (st.isDirectory()) {
throw Object.assign(new Error(`EISDIR: illegal operation on a directory, stat '${path}'`), {
code: "EISDIR",
path,
});
}
return st.size;
}
fileSize.test.js 70 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-size-of-a-file/.
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdir, mkdtemp, open, rm, symlink, truncate, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileSize } from "./fileSize.js";
async function withDir(fn) {
const dir = await mkdtemp(join(tmpdir(), "file-size-"));
try {
await fn(dir);
} finally {
await rm(dir, { recursive: true, force: true });
}
}
const cases = [
["text", "a.txt", Buffer.from("alpha\n"), 6],
["non-ascii-text", "a.txt", Buffer.from("café\n"), 6],
["empty-file", "a.txt", Buffer.alloc(0), 0],
["binary-data", "a.bin", Buffer.from([0x00, 0x0d, 0x0a, 0xc3, 0xbf, 0x00]), 6],
["crlf-line-ends", "a.txt", Buffer.from("a\r\nb\r\n"), 6],
["name-with-spaces", "my notes.txt", Buffer.from("alpha\n"), 6],
["non-ascii-name", "café 日本.txt", Buffer.from("alpha\n"), 6],
];
for (const [name, rel, data, size] of cases) {
test(name, () =>
withDir(async (dir) => {
await writeFile(join(dir, rel), data);
assert.equal(await fileSize(join(dir, rel)), size);
}),
);
}
test("errors", () =>
withDir(async (dir) => {
await assert.rejects(fileSize(join(dir, "a.txt")), { code: "ENOENT" });
await mkdir(join(dir, "dir"));
await assert.rejects(fileSize(join(dir, "dir")), { code: "EISDIR" });
}));
test("symbolic link", () =>
withDir(async (dir) => {
await writeFile(join(dir, "a.txt"), "alpha beta\n");
await symlink("a.txt", join(dir, "link"));
assert.equal(await fileSize(join(dir, "link")), 11);
}));
test("sparse file of 5 GiB", () =>
withDir(async (dir) => {
await writeFile(join(dir, "sparse.bin"), "");
await truncate(join(dir, "sparse.bin"), 5 * 1024 ** 3);
assert.equal(await fileSize(join(dir, "sparse.bin")), 5368709120);
}));
test("open file", () =>
withDir(async (dir) => {
const path = join(dir, "app.log");
const f = await open(path, "w");
try {
await f.write("alpha\n");
assert.equal(await fileSize(path), 6);
} finally {
await f.close();
}
}));
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-size-of-a-file/.
import { stat } from "node:fs/promises";
/**
* Returns the size in bytes of the regular file at path. stat follows a
* symbolic link, so a link gives the size of its target. A missing file
* gives an error with the code ENOENT. stat also gives a size for a
* directory, but it is not the size of a file, so the code throws an error
* with the code EISDIR.
*/
export async function fileSize(path: string): Promise<number> {
const st = await stat(path);
if (st.isDirectory()) {
throw Object.assign(new Error(`EISDIR: illegal operation on a directory, stat '${path}'`), {
code: "EISDIR",
path,
});
}
return st.size;
}
fileSize.test.ts 70 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-size-of-a-file/.
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdir, mkdtemp, open, rm, symlink, truncate, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileSize } from "./fileSize.ts";
async function withDir(fn: (dir: string) => Promise<void>): Promise<void> {
const dir = await mkdtemp(join(tmpdir(), "file-size-"));
try {
await fn(dir);
} finally {
await rm(dir, { recursive: true, force: true });
}
}
const cases: [string, string, Buffer, number][] = [
["text", "a.txt", Buffer.from("alpha\n"), 6],
["non-ascii-text", "a.txt", Buffer.from("café\n"), 6],
["empty-file", "a.txt", Buffer.alloc(0), 0],
["binary-data", "a.bin", Buffer.from([0x00, 0x0d, 0x0a, 0xc3, 0xbf, 0x00]), 6],
["crlf-line-ends", "a.txt", Buffer.from("a\r\nb\r\n"), 6],
["name-with-spaces", "my notes.txt", Buffer.from("alpha\n"), 6],
["non-ascii-name", "café 日本.txt", Buffer.from("alpha\n"), 6],
];
for (const [name, rel, data, size] of cases) {
test(name, () =>
withDir(async (dir) => {
await writeFile(join(dir, rel), data);
assert.equal(await fileSize(join(dir, rel)), size);
}),
);
}
test("errors", () =>
withDir(async (dir) => {
await assert.rejects(fileSize(join(dir, "a.txt")), { code: "ENOENT" });
await mkdir(join(dir, "dir"));
await assert.rejects(fileSize(join(dir, "dir")), { code: "EISDIR" });
}));
test("symbolic link", () =>
withDir(async (dir) => {
await writeFile(join(dir, "a.txt"), "alpha beta\n");
await symlink("a.txt", join(dir, "link"));
assert.equal(await fileSize(join(dir, "link")), 11);
}));
test("sparse file of 5 GiB", () =>
withDir(async (dir) => {
await writeFile(join(dir, "sparse.bin"), "");
await truncate(join(dir, "sparse.bin"), 5 * 1024 ** 3);
assert.equal(await fileSize(join(dir, "sparse.bin")), 5368709120);
}));
test("open file", () =>
withDir(async (dir) => {
const path = join(dir, "app.log");
const f = await open(path, "w");
try {
await f.write("alpha\n");
assert.equal(await fileSize(path), 6);
} finally {
await f.close();
}
}));
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-size-of-a-file/.
// Package filesize gets the size of a file.
package filesize
import (
"io/fs"
"os"
"syscall"
)
// FileSize returns the size in bytes of the regular file at path. os.Stat
// follows a symbolic link, so a link gives the size of its target. A missing
// file gives a *fs.PathError with fs.ErrNotExist. os.Stat also gives a size
// for a directory, but it is not the size of a file, so the code returns a
// *fs.PathError with syscall.EISDIR.
func FileSize(path string) (int64, error) {
fi, err := os.Stat(path)
if err != nil {
return 0, err
}
if fi.IsDir() {
return 0, &fs.PathError{Op: "size", Path: path, Err: syscall.EISDIR}
}
return fi.Size(), nil
}
file_size_test.go 85 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-size-of-a-file/.
package filesize
import (
"errors"
"io/fs"
"os"
"path/filepath"
"syscall"
"testing"
)
func must(t *testing.T, err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}
func TestCases(t *testing.T) {
for _, c := range []struct {
name, path, data string
size int64
}{
{"text", "a.txt", "alpha\n", 6},
{"non-ascii-text", "a.txt", "café\n", 6},
{"empty-file", "a.txt", "", 0},
{"binary-data", "a.bin", "\x00\r\n\xc3\xbf\x00", 6},
{"crlf-line-ends", "a.txt", "a\r\nb\r\n", 6},
{"name-with-spaces", "my notes.txt", "alpha\n", 6},
{"non-ascii-name", "café 日本.txt", "alpha\n", 6},
} {
t.Run(c.name, func(t *testing.T) {
path := filepath.Join(t.TempDir(), c.path)
must(t, os.WriteFile(path, []byte(c.data), 0o644))
got, err := FileSize(path)
if err != nil || got != c.size {
t.Fatalf("FileSize = %d, %v; want %d", got, err, c.size)
}
})
}
}
func TestErrors(t *testing.T) {
dir := t.TempDir()
if _, err := FileSize(filepath.Join(dir, "a.txt")); !errors.Is(err, fs.ErrNotExist) {
t.Errorf("missing: %v", err)
}
must(t, os.Mkdir(filepath.Join(dir, "dir"), 0o755))
if _, err := FileSize(filepath.Join(dir, "dir")); !errors.Is(err, syscall.EISDIR) {
t.Errorf("directory: %v", err)
}
}
func TestSymbolicLink(t *testing.T) {
dir := t.TempDir()
must(t, os.WriteFile(filepath.Join(dir, "a.txt"), []byte("alpha beta\n"), 0o644))
must(t, os.Symlink("a.txt", filepath.Join(dir, "link")))
if got, err := FileSize(filepath.Join(dir, "link")); err != nil || got != 11 {
t.Errorf("link: %d, %v", got, err)
}
}
func TestSparseFileOf5GiB(t *testing.T) {
path := filepath.Join(t.TempDir(), "sparse.bin")
must(t, os.WriteFile(path, nil, 0o644))
must(t, os.Truncate(path, 5<<30))
if got, err := FileSize(path); err != nil || got != 5368709120 {
t.Errorf("sparse: %d, %v", got, err)
}
}
func TestOpenFile(t *testing.T) {
path := filepath.Join(t.TempDir(), "app.log")
f, err := os.Create(path)
must(t, err)
defer f.Close()
_, err = f.WriteString("alpha\n") // an *os.File has no buffer
must(t, err)
if got, err := FileSize(path); err != nil || got != 6 {
t.Errorf("open: %d, %v", got, err)
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-size-of-a-file/.
use std::fs;
use std::io::{self, ErrorKind};
use std::path::Path;
/// Returns the size in bytes of the regular file at `path`. `fs::metadata`
/// follows a symbolic link, so a link gives the size of its target. A missing
/// file gives `ErrorKind::NotFound`. `fs::metadata` also gives a size for a
/// directory, but it is not the size of a file, so the code returns
/// `ErrorKind::IsADirectory`.
pub fn file_size(path: &Path) -> io::Result<u64> {
let meta = fs::metadata(path)?;
if meta.is_dir() {
return Err(io::Error::new(ErrorKind::IsADirectory, format!("{}: is a directory", path.display())));
}
Ok(meta.len())
}
tests/file_size_test.rs 73 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-size-of-a-file/.
use std::fs::{self, File};
use std::io::{ErrorKind, Write};
use std::path::PathBuf;
use algo_get_the_size_of_a_file::file_size;
/// Returns a new, empty directory for one test.
fn new_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("file-size-{}-{name}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn cases() {
for (name, rel, data, size) in [
("text", "a.txt", "alpha\n".as_bytes(), 6),
("non-ascii-text", "a.txt", "café\n".as_bytes(), 6),
("empty-file", "a.txt", b"".as_slice(), 0),
("binary-data", "a.bin", b"\x00\r\n\xc3\xbf\x00".as_slice(), 6),
("crlf-line-ends", "a.txt", b"a\r\nb\r\n".as_slice(), 6),
("name-with-spaces", "my notes.txt", b"alpha\n".as_slice(), 6),
("non-ascii-name", "café 日本.txt", b"alpha\n".as_slice(), 6),
] {
let dir = new_dir(name);
let path = dir.join(rel);
fs::write(&path, data).unwrap();
assert_eq!(file_size(&path).unwrap(), size, "{name}");
fs::remove_dir_all(&dir).unwrap();
}
}
#[test]
fn errors() {
let dir = new_dir("errors");
assert_eq!(file_size(&dir.join("a.txt")).unwrap_err().kind(), ErrorKind::NotFound);
fs::create_dir(dir.join("dir")).unwrap();
assert_eq!(file_size(&dir.join("dir")).unwrap_err().kind(), ErrorKind::IsADirectory);
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn symbolic_link() {
let dir = new_dir("link");
fs::write(dir.join("a.txt"), "alpha beta\n").unwrap();
std::os::unix::fs::symlink("a.txt", dir.join("link")).unwrap();
assert_eq!(file_size(&dir.join("link")).unwrap(), 11);
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn sparse_file_of_5_gib() {
let dir = new_dir("sparse");
let path = dir.join("sparse.bin");
File::create(&path).unwrap().set_len(5 << 30).unwrap();
assert_eq!(file_size(&path).unwrap(), 5368709120);
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn open_file() {
let dir = new_dir("open");
let path = dir.join("app.log");
let mut f = File::create(&path).unwrap(); // a File has no buffer
f.write_all(b"alpha\n").unwrap();
assert_eq!(file_size(&path).unwrap(), 6);
drop(f);
fs::remove_dir_all(&dir).unwrap();
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/get-the-size-of-a-file/.
# file_size PATH
# Prints the size in bytes of the regular file at PATH. POSIX has no stat
# utility, so the function uses wc -c, which counts bytes, not characters.
# The input comes from a redirection, so wc prints no file name, and the
# function removes the spaces that some wc versions put before the number.
# The redirection follows a symbolic link. The function returns status 1 for
# a missing file and for a directory.
file_size() {
if [[ -d $1 ]]; then
printf 'file_size: %s: is a directory\n' "$1" >&2
return 1
fi
if [[ ! -e $1 ]]; then
printf 'file_size: %s: no such file\n' "$1" >&2
return 1
fi
local n
n=$(wc -c <"$1") || return 1
printf '%s\n' "${n//[[:space:]]/}"
}
test_file_size.bats 65 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/get-the-size-of-a-file/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/file_size.sh"
dir=$BATS_TEST_TMPDIR
}
@test "text" {
printf 'alpha\n' >"$dir/a.txt"
[ "$(file_size "$dir/a.txt")" = 6 ]
}
@test "non-ascii-text" {
printf 'caf\303\251\n' >"$dir/a.txt"
[ "$(file_size "$dir/a.txt")" = 6 ]
}
@test "empty-file" {
: >"$dir/a.txt"
[ "$(file_size "$dir/a.txt")" = 0 ]
}
@test "binary-data" {
printf '\000\r\n\303\277\000' >"$dir/a.bin"
[ "$(file_size "$dir/a.bin")" = 6 ]
}
@test "crlf-line-ends" {
printf 'a\r\nb\r\n' >"$dir/a.txt"
[ "$(file_size "$dir/a.txt")" = 6 ]
}
@test "name-with-spaces" {
printf 'alpha\n' >"$dir/my notes.txt"
[ "$(file_size "$dir/my notes.txt")" = 6 ]
}
@test "non-ascii-name" {
printf 'alpha\n' >"$dir/café 日本.txt"
[ "$(file_size "$dir/café 日本.txt")" = 6 ]
}
@test "missing" {
run -1 file_size "$dir/a.txt"
}
@test "directory" {
mkdir "$dir/dir"
run -1 file_size "$dir/dir"
}
@test "symbolic link" {
printf 'alpha beta\n' >"$dir/a.txt"
ln -s a.txt "$dir/link"
[ "$(file_size "$dir/link")" = 11 ]
}
@test "sparse file of 5 GiB" {
dd if=/dev/null of="$dir/sparse.bin" bs=1 seek=5368709120 2>/dev/null
[ "$(file_size "$dir/sparse.bin")" = 5368709120 ]
}
References
- The Python Standard Library, os, Miscellaneous operating system interfaces, os.stat, stat_result.st_size, stat_result.st_blocks
- The Python Standard Library, os.path, Common pathname manipulations, os.path.getsize
- The Python Standard Library, io, Core tools for working with streams, IOBase.flush
- Node.js documentation, File system, Class fs.Stats, stats.size, stats.blocks
- Java SE 25 API, Files, size(Path), readAttributes(Path, Class, LinkOption...)
- .NET API reference, FileInfo.Length Property, Exceptions, Remarks
- .NET API reference, FileSystemInfo.ResolveLinkTarget(Boolean) Method, Description
- Go standard library, package os, func Stat, func (*File) Stat
- The Rust Standard Library, std::fs::Metadata, len
- The Open Group Base Specifications Issue 8 (POSIX.1-2024), sys/stat.h, DESCRIPTION (st_size, st_blocks)
- The Open Group Base Specifications Issue 8 (POSIX.1-2024), wc, OPTIONS (-c, -m), STDOUT
- The Open Group Base Specifications Issue 8 (POSIX.1-2024), du, DESCRIPTION
- cppreference, std::filesystem::file_size, Description
- Windows API reference, GetFileSizeEx function (fileapi.h), Syntax
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 P9HCNV Edit this page History Report an error Markdown