Inside Bitcoin
Opening the selected file…
Inside Bitcoin
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) 2009-2010 Satoshi Nakamoto2// Copyright (c) 2009-present The Bitcoin Core developers3// Distributed under the MIT software license, see the accompanying4// file COPYING or http://www.opensource.org/licenses/mit-license.php.6#ifndef BITCOIN_FLATFILE_H7#define BITCOIN_FLATFILE_H9#include <string>11#include <serialize.h>12#include <util/fs.h>14struct FlatFilePos15{16int32_t nFile{-1};17uint64_t nPos{0};19SERIALIZE_METHODS(FlatFilePos, obj) { READWRITE(VARINT_MODE(obj.nFile, VarIntMode::NONNEGATIVE_SIGNED), VARINT(obj.nPos)); }21FlatFilePos() = default;23FlatFilePos(int32_t nFileIn, uint64_t nPosIn)24: nFile{nFileIn},25nPos{nPosIn}26{}28friend bool operator==(const FlatFilePos &a, const FlatFilePos &b) {29return (a.nFile == b.nFile && a.nPos == b.nPos);30}32bool IsNull() const { return (nFile == -1); }34std::string ToString() const;35};37/**38* FlatFileSeq represents a sequence of numbered files storing raw data. This class facilitates39* access to and efficient management of these files.40*/41class FlatFileSeq42{43private:44const fs::path m_dir;45const char* const m_prefix;46const size_t m_chunk_size;48public:49/**50* Constructor51*52* @param dir The base directory that all files live in.53* @param prefix A short prefix given to all file names.54* @param chunk_size Disk space is pre-allocated in multiples of this amount.55*/56FlatFileSeq(fs::path dir, const char* prefix, size_t chunk_size);58/** Get the name of the file at the given position. */59fs::path FileName(const FlatFilePos& pos) const;61/** Open a handle to the file at the given position. */62FILE* Open(const FlatFilePos& pos, bool read_only = false) const;64/**65* Allocate additional space in a file after the given starting position. The amount allocated66* will be the minimum multiple of the sequence chunk size greater than add_size.67*68* @param[in] pos The starting position that bytes will be allocated after.69* @param[in] add_size The minimum number of bytes to be allocated.70* @param[out] out_of_space Whether the allocation failed due to insufficient disk space.71* @return The number of bytes successfully allocated.72*/73size_t Allocate(const FlatFilePos& pos, size_t add_size, bool& out_of_space) const;75/**76* Commit a file to disk, and optionally truncate off extra pre-allocated bytes if final.77*78* @param[in] pos The first unwritten position in the file to be flushed.79* @param[in] finalize True if no more data will be written to this file.80* @return true on success, false on failure.81*/82bool Flush(const FlatFilePos& pos, bool finalize = false) const;83};85#endif // BITCOIN_FLATFILE_H