Taskcore
Read and write with buffers
Also called buffered input and output, buffered reader and writer, copy a file through a buffer, flush a buffer.
Copy a file through a buffered reader and a buffered writer of a given size, then flush and close the output and report each error, also the error that comes only at the flush.
- Evidence
- Code in 10 languages
Task
Copy a file through a buffered reader and a buffered writer. The function gets the path of the source file, the path of the output file and a buffer size in bytes. It returns the number of bytes copied. After the call, the output file holds exactly the bytes of the source file.
A buffer keeps bytes in memory, so that the program asks the operating system for a large block at a time and not for each small piece. Each call to the operating system costs time, and a disk or a network is fastest with large blocks. A buffered writer sends its bytes to the file only when the buffer is full, at a flush, or at the close. Thus the last bytes go to the file only at the flush or the close, and an error from that last write, such as a full disk, also comes only then. The solution must flush and close the output and report that error.
Report an error if the source file does not exist, if the directory of the output file does not exist, or if the size is below 1. If the output file is there, replace it.
To read a small file in one call, see Read a whole file and Read a binary file. SQL, regular expressions, HTML and CSS do not apply, because they do not open files.
Solutions
Each solution reads the source in a loop. Each read gives at most size bytes, and the loop writes those bytes to the buffered writer and stops at the end of the file.
- Python.
io.BufferedReader(io.FileIO(src, "r"), buffer_size=size)andio.BufferedWriter(io.FileIO(dst, "w"), buffer_size=size)in onewithstatement. "When writing to this object, data is normally placed into an internal buffer." Thewithstatement closes the writer, and the close writes the buffer, so an error from that write comes out of thewithstatement.read1(size)makes at most one read from the file and givesb""at the end. - JavaScript and TypeScript (Node.js).
fsPromises.openfor each file, thenstream.pipelinefromfilehandle.createReadStream({ highWaterMark: size }), through a generator that counts the bytes, tofilehandle.createWriteStream({ highWaterMark: size }). "The highWaterMark option is a threshold, not a limit: it dictates the amount of data that a stream buffers before it stops asking for more data." The promise ofpipelineresolves when the output stream is closed, and it is rejected if a step fails. The code opens the source first, so that a missing source does not make an empty output file. - Java.
new BufferedInputStream(Files.newInputStream(src), size)andnew BufferedOutputStream(Files.newOutputStream(dst), size)in a try-with-resources statement. The close flushes the buffer, and an error from that write comes out of thetryas anIOException. A write of a large array does not go through the buffer: "If the requested length is at least as large as this stream's buffer, however, then this method will flush the buffer and write the bytes directly to the underlying output stream." - C#. Two
FileStreamobjects with thebufferSizeargument, and an explicitFlushbefore the method returns. Then an error from the last write comes out ofCopyand not out ofDispose. The documentation ofbufferSizesays: "A value of 0 or 1 disables buffering." - Go.
bufio.NewReaderSize(in, size)andbufio.NewWriterSize(out, size), a loop ofReadandWrite, thenw.Flush(). "After all data has been written, the client should call the Writer.Flush method to guarantee all data has been forwarded to the underlying io.Writer." A deferred function returns the error ofout.Close()if there is no other error. Abufio.Readeruses at least 16 bytes: "NewReaderSize returns a new Reader whose buffer has at least the specified size." - Rust.
BufReader::with_capacity(size, File::open(src)?)andBufWriter::with_capacity(size, File::create(dst)?), a loop ofreadandwrite_all, thenwriter.into_inner(), which flushes the buffer and gives back the error of that write. Asizeof typeusizecannot be negative, so only 0 is an invalid size there. - C.
fopenfor each file, thensetvbuf(stream, buf, _IOFBF, size)with a buffer that the code allocates. "{_IOFBF} shall cause input/output to be fully buffered." The buffers must live untilfclose, so the code frees them after it. The function checks the result offclose, becausefclosewrites the bytes that are still in the buffer: "Any unwritten buffered data for the stream shall be written to the file". - C++. Two
std::filebufobjects.pubsetbuf(buf, size)comes beforeopen, because the effect ofsetbufon a file that is open is not the same in each library. The loop usessgetnandsputn, and the code checks the result ofclose(): "If any of the function calls made, including the call to std::fclose(), fails, returns a null pointer". The code returnsstd::expected<std::uintmax_t, CopyError>(C++23). - Bash.
dd if="$src" of="$dst" bs="$size". Withbs, dd reads one block and writes it before it reads the next block: "the data returned from each input block shall be written as a separate output block". dd writes the count to standard error, and the last line starts with the number of bytes, with GNU dd and with BSD dd. The function stores that number in a variable that the caller names.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl, with the files in fixtures/. Each case gives the source, the output path and the buffer size, and the expected result is the number of bytes copied. The output file must then hold the same bytes as the source.
text: 17 bytes of text with a buffer of 4096 bytes. All of the bytes stay in the buffer until the close.several-buffers: the same 17 bytes with a buffer of 4 bytes, so the buffer fills 4 times before the end.empty: an empty source gives an empty output file and a count of 0, not an error.smaller-than-buffer,exact-buffer,one-past-buffer: 5, 8 and 9 bytes with a buffer of 8 bytes. These cases test the end of the loop at the edge of the buffer: a read that fills the buffer exactly, and a last read of 1 byte.size-one: a buffer of 1 byte. The copy is slow but correct.binary: the 256 byte values, so that a text mode or a decoder changes the bytes.- Errors, in
cases/errors.jsonl: a missing source, a missing directory for the output, and a size of 0 or -1. A missing source must not make an output file.
The native tests also copy 1 MiB with buffers of 4096 and 4093 bytes, and they replace an output file that is longer than the source. On Linux, they copy 17 bytes and 1 MiB to /dev/full. "Writes to the /dev/full device fail with an ENOSPC error." The 17 bytes stay in the buffer, so the error comes only at the flush or the close, and each solution must report it.
Pitfalls
- No buffer for small writes. Each write to an unbuffered stream is one call to the operating system. This raw stream counts the calls and keeps no bytes:
This code runs but gives a wrong answer on purpose.
import io
class Counter(io.RawIOBase):
"""A raw stream that counts the calls to write and keeps no bytes."""
calls = 0
def writable(self):
return True
def write(self, b):
self.calls += 1
return len(b)
raw = Counter()
for _ in range(1000):
raw.write(b"x") # no buffer: one call to the file for each byte
print("calls:", raw.calls)
calls: 1000
With a BufferedWriter in front of it, the 1000 bytes go to the raw stream in one call, at the close:
import io
class Counter(io.RawIOBase):
"""A raw stream that counts the calls to write and keeps no bytes."""
calls = 0
def writable(self):
return True
def write(self, b):
self.calls += 1
return len(b)
raw = Counter()
with io.BufferedWriter(raw, buffer_size=4096) as out:
for _ in range(1000):
out.write(b"x") # the bytes stay in the buffer
print("calls before the close:", raw.calls)
print("calls after the close:", raw.calls)
calls before the close: 0
calls after the close: 1
- No flush. The bytes in a buffered writer go to the file only at a flush. In Go, the close of the file does not flush the
bufio.Writer, so the bytes are lost with no error:
This code runs but gives a wrong answer on purpose.
package main
import (
"bufio"
"fmt"
"os"
"path/filepath"
)
func main() {
dir, _ := os.MkdirTemp("", "noflush")
defer os.RemoveAll(dir)
path := filepath.Join(dir, "out.txt")
f, _ := os.Create(path)
w := bufio.NewWriter(f)
fmt.Fprintln(w, "alpha")
f.Close() // no w.Flush(): the 6 bytes are still in the buffer
info, _ := os.Stat(path)
fmt.Println(info.Size(), "bytes in the file")
}
0 bytes in the file
- The error comes after the write. A write to a buffered writer only puts the bytes in the buffer, so it succeeds also when the file cannot take them. The error comes at the flush or the close. Here the output is a pipe with no reader, so each write to the pipe fails:
import io
import os
r, w = os.pipe()
os.close(r) # no reader, so each write to the pipe fails
out = io.BufferedWriter(io.FileIO(w, "w"), buffer_size=4096)
print("write gives", out.write(b"alpha\nbeta\ngamma\n"))
try:
out.close() # the 17 bytes go to the pipe only now
except BrokenPipeError as err:
print("close gives", type(err).__name__)
write gives 17
close gives BrokenPipeError
- An error in a destructor is lost. In Rust, a drop of a
BufWriterflushes the buffer, but it ignores an error. "It is critical to call flush before BufWriter is dropped. Though dropping will attempt to flush the contents of the buffer, any errors that happen in the process of dropping will be ignored." Callflushorinto_innerand check the result:
This code runs but gives a wrong answer on purpose.
use std::io::{BufWriter, Write};
fn main() -> std::io::Result<()> {
let (reader, writer) = std::io::pipe()?;
drop(reader); // no reader, so each write to the pipe fails
let mut out = BufWriter::new(writer);
out.write_all(b"alpha\nbeta\ngamma\n")?; // the bytes stay in the buffer
println!("write_all gives Ok");
drop(out); // the flush in drop fails, and drop ignores the error
println!("drop gives no error");
Ok(())
}
write_all gives Ok
drop gives no error
The same is true for the close of a Rust File: "Errors detected on closing are ignored by the implementation of Drop." The C++ destructor of std::filebuf also closes the file with no way to report an error, so the solution calls close() and checks it. In C, check the result of fclose. The Linux manual says: "A careful programmer will check the return value of close(), since it is quite possible that errors on a previous write(2) operation are reported only on the final close() that releases the open file description."
- A buffer that does not live long enough. In C, the buffer that
setvbufgets must exist until the stream is closed. A buffer in a local array of a function that returns beforefclosegives undefined behavior. In C++,pubsetbufbeforeopenhas an effect, but afteropenthe result is not the same in each library.
Related tasks
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-and-write-with-buffers/.
import io
import os
def copy_buffered(src: str | os.PathLike, dst: str | os.PathLike, size: int) -> int:
"""Copies src to dst through buffers of size bytes and returns the byte count.
The with statement closes the writer, and the close flushes the buffer.
An error from that last write comes out of the with statement.
"""
if size < 1:
raise ValueError(f"size must be at least 1, not {size}")
total = 0
with (
io.BufferedReader(io.FileIO(src, "r"), buffer_size=size) as reader,
io.BufferedWriter(io.FileIO(dst, "w"), buffer_size=size) as writer,
):
# read1 makes at most one call to the file; b"" is the end of the file.
while chunk := reader.read1(size):
writer.write(chunk)
total += len(chunk)
return total
test_copy_buffered.py 73 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-and-write-with-buffers/.
import errno
import os
from pathlib import Path
import pytest
from copy_buffered import copy_buffered
TEXT = b"alpha\nbeta\ngamma\n"
CASES = {
"text": (TEXT, 4096),
"several-buffers": (TEXT, 4),
"empty": (b"", 8),
"smaller-than-buffer": (b"12345", 8),
"exact-buffer": (b"12345678", 8),
"one-past-buffer": (b"123456789", 8),
"size-one": (TEXT, 1),
"binary": (bytes(range(256)), 64),
"large": (bytes(range(256)) * 4096, 4096),
"large-odd-buffer": (bytes(range(256)) * 4096, 4093),
}
@pytest.mark.parametrize("name", CASES)
def test_copy(tmp_path: Path, name: str) -> None:
data, size = CASES[name]
src, dst = tmp_path / "in.bin", tmp_path / "out.bin"
src.write_bytes(data)
assert copy_buffered(src, dst, size) == len(data)
assert dst.read_bytes() == data
def test_replaces_a_longer_file(tmp_path: Path) -> None:
src, dst = tmp_path / "in.bin", tmp_path / "out.bin"
src.write_bytes(b"new")
dst.write_bytes(b"old and longer")
assert copy_buffered(src, dst, 8) == 3
assert dst.read_bytes() == b"new"
def test_missing_src(tmp_path: Path) -> None:
with pytest.raises(FileNotFoundError):
copy_buffered(tmp_path / "missing.bin", tmp_path / "out.bin", 8)
assert not (tmp_path / "out.bin").exists()
def test_missing_dst_dir(tmp_path: Path) -> None:
src = tmp_path / "in.bin"
src.write_bytes(TEXT)
with pytest.raises(FileNotFoundError):
copy_buffered(src, tmp_path / "no-such-dir" / "out.bin", 8)
@pytest.mark.parametrize("size", [0, -1])
def test_invalid_size(tmp_path: Path, size: int) -> None:
src = tmp_path / "in.bin"
src.write_bytes(TEXT)
with pytest.raises(ValueError):
copy_buffered(src, tmp_path / "out.bin", size)
@pytest.mark.skipif(not os.path.exists("/dev/full"), reason="no /dev/full")
@pytest.mark.parametrize("data", [TEXT, bytes(1 << 20)], ids=["at-close", "at-write"])
def test_full_device(tmp_path: Path, data: bytes) -> None:
# 17 bytes stay in the buffer, so the error comes only at the close.
src = tmp_path / "in.bin"
src.write_bytes(data)
with pytest.raises(OSError) as err:
copy_buffered(src, "/dev/full", 4096)
assert err.value.errno == errno.ENOSPC
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-with-buffers/.
// since: C++23 (std::expected)
#include "copy_buffered.hpp"
#include <fstream>
#include <ios>
#include <system_error>
#include <vector>
namespace {
// A file that is not there gives not_found. For dst, a missing parent
// directory gives not_found too; a missing dst is no error.
bool missing(const std::filesystem::path& path) {
std::error_code ec;
return std::filesystem::status(path, ec).type() == std::filesystem::file_type::not_found;
}
} // namespace
std::expected<std::uintmax_t, CopyError> copy_buffered(const std::filesystem::path& src,
const std::filesystem::path& dst,
std::streamsize size) {
if (size < 1) return std::unexpected(CopyError::invalid_size);
// The buffers are made before the filebufs, so they live longer.
std::vector<char> in_buf(size), out_buf(size), chunk(size);
std::filebuf in, out;
// pubsetbuf has an effect only before the file is open.
in.pubsetbuf(in_buf.data(), size);
if (!in.open(src, std::ios::in | std::ios::binary)) {
return std::unexpected(missing(src) ? CopyError::not_found : CopyError::cannot_open);
}
out.pubsetbuf(out_buf.data(), size);
if (!out.open(dst, std::ios::out | std::ios::trunc | std::ios::binary)) {
auto dir = dst.has_parent_path() ? dst.parent_path() : std::filesystem::path(".");
return std::unexpected(missing(dir) ? CopyError::not_found : CopyError::cannot_open);
}
std::uintmax_t total = 0;
for (;;) {
// A filebuf gives a short count at the end of the file and also on a
// read error; it does not tell the two apart.
std::streamsize n = in.sgetn(chunk.data(), size);
if (n <= 0) break;
if (out.sputn(chunk.data(), n) != n) return std::unexpected(CopyError::write_failed);
total += static_cast<std::uintmax_t>(n);
}
// close writes the bytes that are still in the buffer; it gives a null
// pointer if that write or the close fails.
if (out.close() == nullptr) return std::unexpected(CopyError::write_failed);
return total;
}
copy_buffered.hpp 18 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-with-buffers/.
// since: C++23 (std::expected)
#pragma once
#include <cstdint>
#include <expected>
#include <filesystem>
enum class CopyError { not_found, cannot_open, invalid_size, write_failed };
// Copies the file at src to the file at dst through std::filebuf buffers of
// size bytes, and returns the number of bytes copied. An error from the last
// write is CopyError::write_failed, from the close of dst.
std::expected<std::uintmax_t, CopyError> copy_buffered(const std::filesystem::path& src,
const std::filesystem::path& dst,
std::streamsize size);
test_copy_buffered.cpp 95 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-with-buffers/.
#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <iterator>
#include <string>
#include <string_view>
#include <vector>
#include "copy_buffered.hpp"
namespace {
const std::filesystem::path src = "copy_buffered_in.bin";
const std::filesystem::path dst = "copy_buffered_out.bin";
void write_file(const std::filesystem::path& path, const std::string& data) {
std::ofstream f(path, std::ios::binary | std::ios::trunc);
f.write(data.data(), static_cast<std::streamsize>(data.size()));
if (!f.flush()) std::abort();
}
std::string read_file(const std::filesystem::path& path) {
std::ifstream f(path, std::ios::binary);
return {std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>()};
}
std::string pattern(std::size_t n) {
std::string s(n, '\0');
for (std::size_t i = 0; i < n; i++) s[i] = static_cast<char>(i & 0xff);
return s;
}
int failures = 0;
void fail(std::string_view name, std::string_view what) {
std::fprintf(stderr, "case %.*s: %.*s\n", static_cast<int>(name.size()), name.data(),
static_cast<int>(what.size()), what.data());
failures++;
}
void check(std::string_view name, const std::string& data, std::streamsize size) {
write_file(src, data);
auto got = copy_buffered(src, dst, size);
if (!got || *got != data.size()) return fail(name, "wrong count or an error");
if (read_file(dst) != data) fail(name, "dst is not the same as src");
}
void check_error(std::string_view name, const std::filesystem::path& from,
const std::filesystem::path& to, std::streamsize size, CopyError want) {
auto got = copy_buffered(from, to, size);
if (got || got.error() != want) fail(name, "wrong result, want an error");
}
} // namespace
int main() {
const std::string text = "alpha\nbeta\ngamma\n";
const std::string large = pattern(1 << 20);
check("text", text, 4096);
check("several-buffers", text, 4);
check("empty", "", 8);
check("smaller-than-buffer", "12345", 8);
check("exact-buffer", "12345678", 8);
check("one-past-buffer", "123456789", 8);
check("size-one", text, 1);
check("binary", pattern(256), 64);
check("large", large, 4096);
check("large-odd-buffer", large, 4093);
write_file(dst, "old and longer");
check("replaces-a-longer-file", "new", 8);
std::filesystem::remove(dst);
check_error("missing-src", "copy_buffered_missing.bin", dst, 8, CopyError::not_found);
if (std::filesystem::exists(dst)) fail("missing-src", "dst was made");
write_file(src, text);
check_error("missing-dst-dir", src, "copy_buffered_no_such_dir/out.bin", 8, CopyError::not_found);
check_error("zero-size", src, dst, 0, CopyError::invalid_size);
check_error("negative-size", src, dst, -1, CopyError::invalid_size);
if (std::filesystem::exists("/dev/full")) {
// 17 bytes stay in the buffer, so the error comes only from close.
check_error("full-device-small", src, "/dev/full", 4096, CopyError::write_failed);
write_file(src, large);
check_error("full-device-large", src, "/dev/full", 4096, CopyError::write_failed);
}
std::filesystem::remove(src);
std::filesystem::remove(dst);
if (failures > 0) return 1;
std::puts("ok");
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-with-buffers/.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
public final class CopyBuffered {
private CopyBuffered() {}
/**
* Copies src to dst through buffers of size bytes and returns the number of bytes copied.
*
* <p>The try statement closes the output, and the close flushes the buffer. An error from that
* last write comes out of the try statement as an IOException.
*/
public static long copy(Path src, Path dst, int size) throws IOException {
if (size < 1) {
throw new IllegalArgumentException("size must be at least 1, not " + size);
}
long total = 0;
try (InputStream in = new BufferedInputStream(Files.newInputStream(src), size);
OutputStream out = new BufferedOutputStream(Files.newOutputStream(dst), size)) {
byte[] chunk = new byte[size];
int n;
while ((n = in.read(chunk)) != -1) {
out.write(chunk, 0, n);
total += n;
}
}
return total;
}
}
CopyBufferedTest.java 110 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-with-buffers/.
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIf;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
class CopyBufferedTest {
@TempDir Path dir;
private static final byte[] TEXT = "alpha\nbeta\ngamma\n".getBytes(StandardCharsets.US_ASCII);
private static byte[] pattern(int n) {
byte[] b = new byte[n];
for (int i = 0; i < n; i++) {
b[i] = (byte) i;
}
return b;
}
private static byte[] ascii(String s) {
return s.getBytes(StandardCharsets.US_ASCII);
}
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("text", TEXT, 4096),
Arguments.of("several-buffers", TEXT, 4),
Arguments.of("empty", new byte[0], 8),
Arguments.of("smaller-than-buffer", ascii("12345"), 8),
Arguments.of("exact-buffer", ascii("12345678"), 8),
Arguments.of("one-past-buffer", ascii("123456789"), 8),
Arguments.of("size-one", TEXT, 1),
Arguments.of("binary", pattern(256), 64),
Arguments.of("large", pattern(1 << 20), 4096),
Arguments.of("large-odd-buffer", pattern(1 << 20), 4093));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void copies(String name, byte[] data, int size) throws IOException {
Path src = Files.write(dir.resolve("in.bin"), data);
Path dst = dir.resolve("out.bin");
assertEquals(data.length, CopyBuffered.copy(src, dst, size));
assertArrayEquals(data, Files.readAllBytes(dst));
}
@Test
void replacesALongerFile() throws IOException {
Path src = Files.write(dir.resolve("in.bin"), ascii("new"));
Path dst = Files.write(dir.resolve("out.bin"), ascii("old and longer"));
assertEquals(3, CopyBuffered.copy(src, dst, 8));
assertArrayEquals(ascii("new"), Files.readAllBytes(dst));
}
@Test
void missingSrc() {
assertThrows(
NoSuchFileException.class,
() -> CopyBuffered.copy(dir.resolve("missing.bin"), dir.resolve("out.bin"), 8));
assertFalse(Files.exists(dir.resolve("out.bin")));
}
@Test
void missingDstDir() throws IOException {
Path src = Files.write(dir.resolve("in.bin"), TEXT);
assertThrows(
NoSuchFileException.class,
() -> CopyBuffered.copy(src, dir.resolve("no-such-dir").resolve("out.bin"), 8));
}
@ParameterizedTest
@ValueSource(ints = {0, -1})
void invalidSize(int size) throws IOException {
Path src = Files.write(dir.resolve("in.bin"), TEXT);
assertThrows(
IllegalArgumentException.class, () -> CopyBuffered.copy(src, dir.resolve("out.bin"), size));
}
static boolean hasFullDevice() {
return Files.exists(Path.of("/dev/full"));
}
@ParameterizedTest
@ValueSource(ints = {17, 1 << 20})
@EnabledIf("hasFullDevice")
void fullDevice(int n) throws IOException {
// 17 bytes stay in the buffer, so the error comes only at the close.
Path src = Files.write(dir.resolve("in.bin"), pattern(n));
IOException err =
assertThrows(IOException.class, () -> CopyBuffered.copy(src, Path.of("/dev/full"), 4096));
assertTrue(String.valueOf(err.getMessage()).contains("No space left"), err.getMessage());
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-with-buffers/.
#include "copy_buffered.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
long long copy_buffered(const char *src, const char *dst, long size) {
if (size < 1) {
errno = EINVAL;
return -1;
}
FILE *in = fopen(src, "rb");
if (in == NULL) return -1;
FILE *out = fopen(dst, "wb");
if (out == NULL) {
int err = errno;
fclose(in);
errno = err;
return -1;
}
// The buffers must live until fclose, so they are freed after it.
char *in_buf = malloc((size_t)size);
char *out_buf = malloc((size_t)size);
char *chunk = malloc((size_t)size);
long long total = -1;
int err = 0;
if (in_buf == NULL || out_buf == NULL || chunk == NULL) {
err = ENOMEM;
} else if (setvbuf(in, in_buf, _IOFBF, (size_t)size) != 0 ||
setvbuf(out, out_buf, _IOFBF, (size_t)size) != 0) {
err = errno != 0 ? errno : EINVAL;
} else {
total = 0;
size_t n;
while ((n = fread(chunk, 1, (size_t)size, in)) > 0) {
if (fwrite(chunk, 1, n, out) != n) {
err = errno;
total = -1;
break;
}
total += (long long)n;
}
if (total >= 0 && ferror(in)) {
err = errno;
total = -1;
}
}
fclose(in);
if (fclose(out) != 0 && total >= 0) {
err = errno;
total = -1;
}
free(in_buf);
free(out_buf);
free(chunk);
if (total < 0) errno = err;
return total;
}
copy_buffered.h 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-with-buffers/.
#ifndef COPY_BUFFERED_H
#define COPY_BUFFERED_H
// copy_buffered copies the file at src to the file at dst through stdio
// buffers of size bytes, and returns the number of bytes copied. On an error
// it returns -1 and sets errno: EINVAL if size is below 1, or the error of
// fopen, fread, fwrite or fclose. An error from the last write comes from
// fclose, because fclose writes the bytes that are still in the buffer.
long long copy_buffered(const char *src, const char *dst, long size);
#endif
test_copy_buffered.c 100 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-with-buffers/.
// access is in POSIX.1-2008, not in ISO C.
#define _POSIX_C_SOURCE 200809L
#include "copy_buffered.h"
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static const char *src = "copy_buffered_in.bin";
static const char *dst = "copy_buffered_out.bin";
static void write_file(const char *path, const unsigned char *data, size_t n) {
FILE *f = fopen(path, "wb");
assert(f != NULL);
assert(fwrite(data, 1, n, f) == n);
assert(fclose(f) == 0);
}
static unsigned char *pattern(size_t n) {
unsigned char *b = malloc(n > 0 ? n : 1);
assert(b != NULL);
for (size_t i = 0; i < n; i++) b[i] = (unsigned char)i;
return b;
}
static void check(const char *name, const unsigned char *data, size_t n, long size) {
write_file(src, data, n);
long long got = copy_buffered(src, dst, size);
if (got != (long long)n) {
fprintf(stderr, "case %s: copy_buffered = %lld, want %zu\n", name, got, n);
exit(1);
}
FILE *f = fopen(dst, "rb");
assert(f != NULL);
unsigned char *back = malloc(n + 1);
assert(back != NULL);
size_t m = fread(back, 1, n + 1, f);
fclose(f);
if (m != n || memcmp(back, data, n) != 0) {
fprintf(stderr, "case %s: dst is not the same as src\n", name);
exit(1);
}
free(back);
}
static void check_error(const char *name, const char *from, const char *to, long size, int want) {
errno = 0;
long long got = copy_buffered(from, to, size);
if (got != -1 || errno != want) {
fprintf(stderr, "case %s: copy_buffered = %lld, errno %d, want -1, errno %d\n", name, got, errno, want);
exit(1);
}
}
int main(void) {
const unsigned char *text = (const unsigned char *)"alpha\nbeta\ngamma\n";
unsigned char *all = pattern(256);
unsigned char *large = pattern(1 << 20);
check("text", text, 17, 4096);
check("several-buffers", text, 17, 4);
check("empty", (const unsigned char *)"", 0, 8);
check("smaller-than-buffer", (const unsigned char *)"12345", 5, 8);
check("exact-buffer", (const unsigned char *)"12345678", 8, 8);
check("one-past-buffer", (const unsigned char *)"123456789", 9, 8);
check("size-one", text, 17, 1);
check("binary", all, 256, 64);
check("large", large, 1 << 20, 4096);
check("large-odd-buffer", large, 1 << 20, 4093);
write_file(dst, (const unsigned char *)"old and longer", 14);
check("replaces-a-longer-file", (const unsigned char *)"new", 3, 8);
remove(dst);
check_error("missing-src", "copy_buffered_missing.bin", dst, 8, ENOENT);
assert(access(dst, F_OK) != 0);
write_file(src, text, 17);
check_error("missing-dst-dir", src, "copy_buffered_no_such_dir/out.bin", 8, ENOENT);
check_error("zero-size", src, dst, 0, EINVAL);
check_error("negative-size", src, dst, -1, EINVAL);
if (access("/dev/full", F_OK) == 0) {
// 17 bytes stay in the buffer, so the error comes only from fclose.
check_error("full-device-small", src, "/dev/full", 4096, ENOSPC);
write_file(src, large, 1 << 20);
check_error("full-device-large", src, "/dev/full", 4096, ENOSPC);
}
remove(src);
remove(dst);
free(all);
free(large);
puts("ok");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-with-buffers/.
public static class CopyBuffered
{
/// <summary>
/// Copies src to dst through buffers of size bytes and returns the number of bytes copied.
/// </summary>
/// <remarks>
/// The explicit Flush writes the last bytes in the buffer, so that an error from that
/// write comes out of this method and not out of Dispose.
/// </remarks>
public static long Copy(string src, string dst, int size)
{
ArgumentOutOfRangeException.ThrowIfLessThan(size, 1);
using var input = new FileStream(src, FileMode.Open, FileAccess.Read, FileShare.Read, size);
using var output = new FileStream(dst, FileMode.Create, FileAccess.Write, FileShare.None, size);
var chunk = new byte[size];
long total = 0;
int n;
while ((n = input.Read(chunk, 0, chunk.Length)) > 0)
{
output.Write(chunk, 0, n);
total += n;
}
output.Flush();
return total;
}
}
CopyBufferedTests.cs 97 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-with-buffers/.
using Xunit;
public sealed class CopyBufferedTests : IDisposable
{
private readonly string dir = Directory.CreateTempSubdirectory("copy-buffered-").FullName;
public void Dispose() => Directory.Delete(dir, recursive: true);
private static readonly byte[] Text = "alpha\nbeta\ngamma\n"u8.ToArray();
private static byte[] Pattern(int n) => Enumerable.Range(0, n).Select(i => (byte)i).ToArray();
private static readonly Dictionary<string, (byte[] Data, int Size)> Cases = new()
{
["text"] = (Text, 4096),
["several-buffers"] = (Text, 4),
["empty"] = ([], 8),
["smaller-than-buffer"] = ("12345"u8.ToArray(), 8),
["exact-buffer"] = ("12345678"u8.ToArray(), 8),
["one-past-buffer"] = ("123456789"u8.ToArray(), 8),
["size-one"] = (Text, 1),
["binary"] = (Pattern(256), 64),
["large"] = (Pattern(1 << 20), 4096),
["large-odd-buffer"] = (Pattern(1 << 20), 4093),
};
public static TheoryData<string> Names => new(Cases.Keys);
private string Write(string name, byte[] data)
{
string path = Path.Combine(dir, name);
File.WriteAllBytes(path, data);
return path;
}
[Theory]
[MemberData(nameof(Names))]
public void Copies(string name)
{
var (data, size) = Cases[name];
string src = Write("in.bin", data);
string dst = Path.Combine(dir, "out.bin");
Assert.Equal(data.Length, CopyBuffered.Copy(src, dst, size));
Assert.Equal(data, File.ReadAllBytes(dst));
}
[Fact]
public void ReplacesALongerFile()
{
string src = Write("in.bin", "new"u8.ToArray());
string dst = Write("out.bin", "old and longer"u8.ToArray());
Assert.Equal(3, CopyBuffered.Copy(src, dst, 8));
Assert.Equal("new"u8.ToArray(), File.ReadAllBytes(dst));
}
[Fact]
public void MissingSrc()
{
Assert.Throws<FileNotFoundException>(
() => CopyBuffered.Copy(Path.Combine(dir, "missing.bin"), Path.Combine(dir, "out.bin"), 8));
Assert.False(File.Exists(Path.Combine(dir, "out.bin")));
}
[Fact]
public void MissingDstDir()
{
string src = Write("in.bin", Text);
Assert.Throws<DirectoryNotFoundException>(
() => CopyBuffered.Copy(src, Path.Combine(dir, "no-such-dir", "out.bin"), 8));
}
[Theory]
[InlineData(0)]
[InlineData(-1)]
public void InvalidSize(int size)
{
string src = Write("in.bin", Text);
Assert.Throws<ArgumentOutOfRangeException>(() => CopyBuffered.Copy(src, Path.Combine(dir, "out.bin"), size));
}
[Theory]
[InlineData(17)]
[InlineData(1 << 20)]
public void FullDevice(int n)
{
if (!File.Exists("/dev/full"))
{
return;
}
// 17 bytes stay in the buffer, so the error comes only at the flush.
string src = Write("in.bin", Pattern(n));
Assert.ThrowsAny<IOException>(() => CopyBuffered.Copy(src, "/dev/full", 4096));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-with-buffers/.
import { open } from "node:fs/promises";
import { pipeline } from "node:stream/promises";
/**
* Copies src to dst through streams with buffers of size bytes, and gives
* the number of bytes copied. The promise is rejected if a read, a write or
* the close of dst fails.
*/
export async function copyBuffered(src, dst, size) {
if (!Number.isInteger(size) || size < 1) {
throw new RangeError(`size must be an integer of at least 1, not ${size}`);
}
// Open src first, so that a missing src does not make an empty dst.
const input = await open(src, "r");
let output;
try {
output = await open(dst, "w");
} catch (err) {
await input.close();
throw err;
}
let total = 0;
// pipeline waits until dst is written and closed, and it closes both
// files if one of the steps fails.
await pipeline(
input.createReadStream({ highWaterMark: size }),
async function* (chunks) {
for await (const chunk of chunks) {
total += chunk.length;
yield chunk;
}
},
output.createWriteStream({ highWaterMark: size }),
);
return total;
}
copyBuffered.test.js 88 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-with-buffers/.
import { test } from "node:test";
import assert from "node:assert/strict";
import { existsSync } from "node:fs";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { copyBuffered } from "./copyBuffered.js";
const text = Buffer.from("alpha\nbeta\ngamma\n");
const allBytes = Buffer.from(Array.from({ length: 256 }, (_, i) => i));
const large = Buffer.concat(Array(4096).fill(allBytes));
const cases = {
text: [text, 4096],
"several-buffers": [text, 4],
empty: [Buffer.alloc(0), 8],
"smaller-than-buffer": [Buffer.from("12345"), 8],
"exact-buffer": [Buffer.from("12345678"), 8],
"one-past-buffer": [Buffer.from("123456789"), 8],
"size-one": [text, 1],
binary: [allBytes, 64],
large: [large, 4096],
"large-odd-buffer": [large, 4093],
};
async function withDir(fn) {
const dir = await mkdtemp(join(tmpdir(), "copy-buffered-"));
try {
await fn(dir);
} finally {
await rm(dir, { recursive: true, force: true });
}
}
for (const [name, [data, size]] of Object.entries(cases)) {
test(name, () =>
withDir(async (dir) => {
const src = join(dir, "in.bin");
const dst = join(dir, "out.bin");
await writeFile(src, data);
assert.equal(await copyBuffered(src, dst, size), data.length);
assert.deepEqual(await readFile(dst), data);
}));
}
test("replaces a longer file", () =>
withDir(async (dir) => {
const src = join(dir, "in.bin");
const dst = join(dir, "out.bin");
await writeFile(src, "new");
await writeFile(dst, "old and longer");
assert.equal(await copyBuffered(src, dst, 8), 3);
assert.equal(await readFile(dst, "utf8"), "new");
}));
test("missing src", () =>
withDir(async (dir) => {
await assert.rejects(copyBuffered(join(dir, "missing.bin"), join(dir, "out.bin"), 8), { code: "ENOENT" });
assert.equal(existsSync(join(dir, "out.bin")), false);
}));
test("missing dst dir", () =>
withDir(async (dir) => {
const src = join(dir, "in.bin");
await writeFile(src, text);
await assert.rejects(copyBuffered(src, join(dir, "no-such-dir", "out.bin"), 8), { code: "ENOENT" });
}));
for (const size of [0, -1, 1.5]) {
test(`invalid size ${size}`, () =>
withDir(async (dir) => {
const src = join(dir, "in.bin");
await writeFile(src, text);
await assert.rejects(copyBuffered(src, join(dir, "out.bin"), size), RangeError);
}));
}
for (const [name, data] of [["full device, small", text], ["full device, large", large]]) {
test(name, { skip: !existsSync("/dev/full") && "no /dev/full" }, () =>
withDir(async (dir) => {
const src = join(dir, "in.bin");
await writeFile(src, data);
await assert.rejects(copyBuffered(src, "/dev/full", 4096), { code: "ENOSPC" });
}));
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-with-buffers/.
import { open, type FileHandle } from "node:fs/promises";
import { pipeline } from "node:stream/promises";
/**
* Copies src to dst through streams with buffers of size bytes, and gives
* the number of bytes copied. The promise is rejected if a read, a write or
* the close of dst fails.
*/
export async function copyBuffered(src: string, dst: string, size: number): Promise<number> {
if (!Number.isInteger(size) || size < 1) {
throw new RangeError(`size must be an integer of at least 1, not ${size}`);
}
// Open src first, so that a missing src does not make an empty dst.
const input = await open(src, "r");
let output: FileHandle;
try {
output = await open(dst, "w");
} catch (err) {
await input.close();
throw err;
}
let total = 0;
// pipeline waits until dst is written and closed, and it closes both
// files if one of the steps fails.
await pipeline(
input.createReadStream({ highWaterMark: size }),
async function* (chunks: AsyncIterable<Buffer>) {
for await (const chunk of chunks) {
total += chunk.length;
yield chunk;
}
},
output.createWriteStream({ highWaterMark: size }),
);
return total;
}
copyBuffered.test.ts 88 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-with-buffers/.
import { test } from "node:test";
import assert from "node:assert/strict";
import { existsSync } from "node:fs";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { copyBuffered } from "./copyBuffered.ts";
const text = Buffer.from("alpha\nbeta\ngamma\n");
const allBytes = Buffer.from(Array.from({ length: 256 }, (_, i) => i));
const large = Buffer.concat(Array(4096).fill(allBytes));
const cases: Record<string, [Buffer, number]> = {
text: [text, 4096],
"several-buffers": [text, 4],
empty: [Buffer.alloc(0), 8],
"smaller-than-buffer": [Buffer.from("12345"), 8],
"exact-buffer": [Buffer.from("12345678"), 8],
"one-past-buffer": [Buffer.from("123456789"), 8],
"size-one": [text, 1],
binary: [allBytes, 64],
large: [large, 4096],
"large-odd-buffer": [large, 4093],
};
async function withDir(fn: (dir: string) => Promise<void>): Promise<void> {
const dir = await mkdtemp(join(tmpdir(), "copy-buffered-"));
try {
await fn(dir);
} finally {
await rm(dir, { recursive: true, force: true });
}
}
for (const [name, [data, size]] of Object.entries(cases)) {
test(name, () =>
withDir(async (dir) => {
const src = join(dir, "in.bin");
const dst = join(dir, "out.bin");
await writeFile(src, data);
assert.equal(await copyBuffered(src, dst, size), data.length);
assert.deepEqual(await readFile(dst), data);
}));
}
test("replaces a longer file", () =>
withDir(async (dir) => {
const src = join(dir, "in.bin");
const dst = join(dir, "out.bin");
await writeFile(src, "new");
await writeFile(dst, "old and longer");
assert.equal(await copyBuffered(src, dst, 8), 3);
assert.equal(await readFile(dst, "utf8"), "new");
}));
test("missing src", () =>
withDir(async (dir) => {
await assert.rejects(copyBuffered(join(dir, "missing.bin"), join(dir, "out.bin"), 8), { code: "ENOENT" });
assert.equal(existsSync(join(dir, "out.bin")), false);
}));
test("missing dst dir", () =>
withDir(async (dir) => {
const src = join(dir, "in.bin");
await writeFile(src, text);
await assert.rejects(copyBuffered(src, join(dir, "no-such-dir", "out.bin"), 8), { code: "ENOENT" });
}));
for (const size of [0, -1, 1.5]) {
test(`invalid size ${size}`, () =>
withDir(async (dir) => {
const src = join(dir, "in.bin");
await writeFile(src, text);
await assert.rejects(copyBuffered(src, join(dir, "out.bin"), size), RangeError);
}));
}
for (const [name, data] of [["full device, small", text], ["full device, large", large]] as const) {
test(name, { skip: !existsSync("/dev/full") && "no /dev/full" }, () =>
withDir(async (dir) => {
const src = join(dir, "in.bin");
await writeFile(src, data);
await assert.rejects(copyBuffered(src, "/dev/full", 4096), { code: "ENOSPC" });
}));
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-with-buffers/.
// Package copybuffered copies a file through a buffered reader and a
// buffered writer.
package copybuffered
import (
"bufio"
"errors"
"io"
"os"
)
// ErrInvalidSize is the error for a buffer size below 1.
var ErrInvalidSize = errors.New("copybuffered: size must be at least 1")
// CopyBuffered copies src to dst through buffers of size bytes and returns
// the number of bytes copied. bufio uses at least 16 bytes for a Reader.
//
// The bytes that are still in the Writer go to the file only at Flush, so
// the error of Flush is the error of the last write. The error of Close is
// returned too.
func CopyBuffered(src, dst string, size int) (n int64, err error) {
if size < 1 {
return 0, ErrInvalidSize
}
in, err := os.Open(src)
if err != nil {
return 0, err
}
defer in.Close()
out, err := os.Create(dst)
if err != nil {
return 0, err
}
defer func() {
if cerr := out.Close(); err == nil {
err = cerr
}
}()
r := bufio.NewReaderSize(in, size)
w := bufio.NewWriterSize(out, size)
chunk := make([]byte, size)
for {
m, rerr := r.Read(chunk)
if m > 0 {
if _, werr := w.Write(chunk[:m]); werr != nil {
return n, werr
}
n += int64(m)
}
if rerr == io.EOF {
break
}
if rerr != nil {
return n, rerr
}
}
return n, w.Flush()
}
copy_buffered_test.go 122 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-with-buffers/.
package copybuffered
import (
"bytes"
"errors"
"io/fs"
"os"
"path/filepath"
"syscall"
"testing"
)
func pattern(n int) []byte {
b := make([]byte, n)
for i := range b {
b[i] = byte(i)
}
return b
}
var text = []byte("alpha\nbeta\ngamma\n")
var cases = []struct {
name string
data []byte
size int
}{
{"text", text, 4096},
{"several-buffers", text, 4},
{"empty", []byte{}, 8},
{"smaller-than-buffer", []byte("12345"), 8},
{"exact-buffer", []byte("12345678"), 8},
{"one-past-buffer", []byte("123456789"), 8},
{"size-one", text, 1},
{"binary", pattern(256), 64},
{"large", pattern(1 << 20), 4096},
{"large-odd-buffer", pattern(1 << 20), 4093},
}
func write(t *testing.T, name string, data []byte) string {
t.Helper()
path := filepath.Join(t.TempDir(), name)
if err := os.WriteFile(path, data, 0o644); err != nil {
t.Fatal(err)
}
return path
}
func TestCopy(t *testing.T) {
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
src := write(t, "in.bin", c.data)
dst := filepath.Join(filepath.Dir(src), "out.bin")
n, err := CopyBuffered(src, dst, c.size)
if err != nil || n != int64(len(c.data)) {
t.Fatalf("CopyBuffered = %d, %v; want %d, nil", n, err, len(c.data))
}
got, err := os.ReadFile(dst)
if err != nil || !bytes.Equal(got, c.data) {
t.Fatalf("dst has %d bytes that are not the same as src (%v)", len(got), err)
}
})
}
}
func TestReplacesALongerFile(t *testing.T) {
src := write(t, "in.bin", []byte("new"))
dst := filepath.Join(filepath.Dir(src), "out.bin")
if err := os.WriteFile(dst, []byte("old and longer"), 0o644); err != nil {
t.Fatal(err)
}
if n, err := CopyBuffered(src, dst, 8); n != 3 || err != nil {
t.Fatalf("CopyBuffered = %d, %v", n, err)
}
if got, _ := os.ReadFile(dst); string(got) != "new" {
t.Fatalf("dst = %q", got)
}
}
func TestMissingSrc(t *testing.T) {
dir := t.TempDir()
_, err := CopyBuffered(filepath.Join(dir, "missing.bin"), filepath.Join(dir, "out.bin"), 8)
if !errors.Is(err, fs.ErrNotExist) {
t.Fatalf("err = %v, want fs.ErrNotExist", err)
}
if _, err := os.Stat(filepath.Join(dir, "out.bin")); !errors.Is(err, fs.ErrNotExist) {
t.Fatalf("dst was made")
}
}
func TestMissingDstDir(t *testing.T) {
src := write(t, "in.bin", text)
_, err := CopyBuffered(src, filepath.Join(filepath.Dir(src), "no-such-dir", "out.bin"), 8)
if !errors.Is(err, fs.ErrNotExist) {
t.Fatalf("err = %v, want fs.ErrNotExist", err)
}
}
func TestInvalidSize(t *testing.T) {
src := write(t, "in.bin", text)
for _, size := range []int{0, -1} {
if _, err := CopyBuffered(src, filepath.Join(filepath.Dir(src), "out.bin"), size); !errors.Is(err, ErrInvalidSize) {
t.Fatalf("size %d: err = %v", size, err)
}
}
}
func TestFullDevice(t *testing.T) {
if _, err := os.Stat("/dev/full"); err != nil {
t.Skip("no /dev/full")
}
// 17 bytes stay in the buffer, so the error comes only at Flush.
for _, n := range []int{17, 1 << 20} {
src := write(t, "in.bin", pattern(n))
if _, err := CopyBuffered(src, "/dev/full", 4096); !errors.Is(err, syscall.ENOSPC) {
t.Fatalf("%d bytes: err = %v, want ENOSPC", n, err)
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-with-buffers/.
use std::fs::File;
use std::io::{self, BufReader, BufWriter, ErrorKind, Read, Write};
use std::path::Path;
/// Copies `src` to `dst` through buffers of `size` bytes and returns the
/// number of bytes copied.
///
/// `into_inner` flushes the `BufWriter` and gives back the error of that
/// last write. A drop of the `BufWriter` also flushes, but it ignores the
/// error.
pub fn copy_buffered(src: impl AsRef<Path>, dst: impl AsRef<Path>, size: usize) -> io::Result<u64> {
if size == 0 {
return Err(io::Error::new(ErrorKind::InvalidInput, "size must be at least 1"));
}
let mut reader = BufReader::with_capacity(size, File::open(src)?);
let mut writer = BufWriter::with_capacity(size, File::create(dst)?);
let mut chunk = vec![0; size];
let mut total = 0;
loop {
let n = match reader.read(&mut chunk) {
Ok(0) => break,
Ok(n) => n,
Err(e) if e.kind() == ErrorKind::Interrupted => continue,
Err(e) => return Err(e),
};
writer.write_all(&chunk[..n])?;
total += n as u64;
}
writer.into_inner().map_err(|e| e.into_error())?;
Ok(total)
}
tests/copy_buffered_test.rs 104 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-with-buffers/.
use std::fs;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use algo_read_and_write_with_buffers::copy_buffered;
const TEXT: &[u8] = b"alpha\nbeta\ngamma\n";
/// Returns a new empty directory for one test.
fn temp_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("copy-buffered-{}-{name}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
dir
}
fn pattern(n: usize) -> Vec<u8> {
(0..n).map(|i| i as u8).collect()
}
fn check(name: &str, data: &[u8], size: usize) {
let dir = temp_dir(name);
let (src, dst) = (dir.join("in.bin"), dir.join("out.bin"));
fs::write(&src, data).unwrap();
assert_eq!(copy_buffered(&src, &dst, size).unwrap(), data.len() as u64, "{name}");
assert!(fs::read(&dst).unwrap() == data, "{name}: dst is not the same as src");
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn copies() {
let cases: [(&str, Vec<u8>, usize); 10] = [
("text", TEXT.to_vec(), 4096),
("several-buffers", TEXT.to_vec(), 4),
("empty", Vec::new(), 8),
("smaller-than-buffer", b"12345".to_vec(), 8),
("exact-buffer", b"12345678".to_vec(), 8),
("one-past-buffer", b"123456789".to_vec(), 8),
("size-one", TEXT.to_vec(), 1),
("binary", pattern(256), 64),
("large", pattern(1 << 20), 4096),
("large-odd-buffer", pattern(1 << 20), 4093),
];
for (name, data, size) in &cases {
check(name, data, *size);
}
}
#[test]
fn replaces_a_longer_file() {
let dir = temp_dir("replace");
let (src, dst) = (dir.join("in.bin"), dir.join("out.bin"));
fs::write(&src, "new").unwrap();
fs::write(&dst, "old and longer").unwrap();
assert_eq!(copy_buffered(&src, &dst, 8).unwrap(), 3);
assert_eq!(fs::read(&dst).unwrap(), b"new");
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn missing_src() {
let dir = temp_dir("missing-src");
let err = copy_buffered(dir.join("missing.bin"), dir.join("out.bin"), 8).unwrap_err();
assert_eq!(err.kind(), ErrorKind::NotFound);
assert!(!dir.join("out.bin").exists());
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn missing_dst_dir() {
let dir = temp_dir("missing-dst-dir");
fs::write(dir.join("in.bin"), TEXT).unwrap();
let err = copy_buffered(dir.join("in.bin"), dir.join("no-such-dir").join("out.bin"), 8).unwrap_err();
assert_eq!(err.kind(), ErrorKind::NotFound);
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn zero_size() {
// A usize cannot be negative, so -1 is not a case here.
let dir = temp_dir("zero-size");
fs::write(dir.join("in.bin"), TEXT).unwrap();
let err = copy_buffered(dir.join("in.bin"), dir.join("out.bin"), 0).unwrap_err();
assert_eq!(err.kind(), ErrorKind::InvalidInput);
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn full_device() {
if !Path::new("/dev/full").exists() {
return;
}
// 17 bytes stay in the buffer, so the error comes only at the flush.
let dir = temp_dir("full");
for n in [17, 1 << 20] {
fs::write(dir.join("in.bin"), pattern(n)).unwrap();
let err = copy_buffered(dir.join("in.bin"), "/dev/full", 4096).unwrap_err();
assert_eq!(err.raw_os_error(), Some(28), "{n} bytes: {err}"); // ENOSPC is 28 on Linux.
}
fs::remove_dir_all(&dir).unwrap();
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-and-write-with-buffers/.
# copy_buffered NAME SRC DST SIZE
# Copies the file SRC to DST with dd, in blocks of SIZE bytes, and stores the
# number of bytes copied in the variable NAME. dd reads one block and writes
# it before it reads the next one. Returns status 2 if SIZE is not a whole
# number of at least 1, and status 1 if dd fails, for example on a missing
# file or a full disk. NAME is not set on an error.
copy_buffered() {
local _copy_buffered
if [[ ! $4 =~ ^[0-9]+$ ]] || ((10#$4 < 1)); then
printf 'copy_buffered: %s: size must be a whole number of at least 1\n' "$4" >&2
return 2
fi
# dd writes its count to stderr; the last line starts with the number of
# bytes, with GNU dd and with BSD dd.
if ! _copy_buffered=$(dd if="$2" of="$3" bs="$((10#$4))" 2>&1); then
printf '%s\n' "$_copy_buffered" >&2
return 1
fi
_copy_buffered=${_copy_buffered##*$'\n'}
printf -v "$1" '%s' "${_copy_buffered%% *}"
}
test_copy_buffered.bats 69 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-and-write-with-buffers/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/copy_buffered.sh"
src="$BATS_TEST_TMPDIR/in.bin"
dst="$BATS_TEST_TMPDIR/out.bin"
}
check() { # check SIZE: copy src to dst and compare
local n want
want=$(wc -c <"$src")
copy_buffered n "$src" "$dst" "$1"
[ "$n" -eq "$want" ]
cmp -s "$src" "$dst"
}
text() { printf 'alpha\nbeta\ngamma\n' >"$src"; }
# all_bytes N: write N copies of the 256 byte values to src.
all_bytes() {
local i esc=''
for ((i = 0; i < 256; i++)); do esc+=$(printf '\\%03o' "$i"); done
printf "$esc" >"$BATS_TEST_TMPDIR/block.bin"
for ((i = 0; i < $1; i++)); do cat "$BATS_TEST_TMPDIR/block.bin"; done >"$src"
}
@test "text" { text; check 4096; }
@test "several buffers" { text; check 4; }
@test "empty" { : >"$src"; check 8; }
@test "smaller than buffer" { printf 12345 >"$src"; check 8; }
@test "exact buffer" { printf 12345678 >"$src"; check 8; }
@test "one past buffer" { printf 123456789 >"$src"; check 8; }
@test "size one" { text; check 1; }
@test "binary" { all_bytes 1; [ "$(wc -c <"$src")" -eq 256 ]; check 64; }
@test "large" { all_bytes 4096; check 4096; }
@test "large, odd buffer" { all_bytes 4096; check 4093; }
@test "replaces a longer file" {
printf new >"$src"
printf 'old and longer' >"$dst"
check 8
}
@test "missing src" {
run -1 copy_buffered n "$BATS_TEST_TMPDIR/missing.bin" "$dst" 8
[ ! -e "$dst" ]
}
@test "missing dst dir" {
text
run -1 copy_buffered n "$src" "$BATS_TEST_TMPDIR/no-such-dir/out.bin" 8
}
@test "invalid size" {
text
run -2 copy_buffered n "$src" "$dst" 0
run -2 copy_buffered n "$src" "$dst" -1
run -2 copy_buffered n "$src" "$dst" 4k
}
@test "full device" {
[ -e /dev/full ] || skip "no /dev/full"
text
run -1 copy_buffered n "$src" /dev/full 4096
}
References
- The Python Standard Library, io, Core tools for working with streams, BufferedReader, BufferedWriter, BufferedIOBase.read1
- Node.js documentation, Stream, Buffering; stream.pipeline(source[, ...transforms], destination[, options])
- Node.js documentation, File system, filehandle.createReadStream([options]), filehandle.createWriteStream([options])
- Java SE 25 API, BufferedOutputStream, BufferedOutputStream(OutputStream out, int size), write(byte[] b, int off, int len)
- Java SE 25 API, BufferedInputStream, BufferedInputStream(InputStream in, int size)
- .NET API reference, FileStream Constructors, FileStream(String, FileMode, FileAccess, FileShare, Int32), the bufferSize parameter
- Go standard library, package bufio, type Writer, NewReaderSize, NewWriterSize, Writer.Flush
- The Rust Standard Library, std::io::BufWriter, the struct documentation, into_inner
- The Rust Standard Library, std::io::BufReader, with_capacity
- The Rust Standard Library, std::fs::File, the struct documentation, sync_all
- The Open Group Base Specifications Issue 8 (POSIX.1-2024), setvbuf, DESCRIPTION
- The Open Group Base Specifications Issue 8 (POSIX.1-2024), fclose, DESCRIPTION
- Linux manual page, close(2), NOTES, Dealing with error returns from close()
- Linux manual page, full(4), DESCRIPTION
- cppreference, std::basic_filebuf::setbuf, Notes
- cppreference, std::basic_filebuf::close, Return value
- The Open Group Base Specifications Issue 8 (POSIX.1-2024), dd, DESCRIPTION, OPERANDS (bs=expr)
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 2ADZBJ Edit this page History Report an error Markdown