File I/O
This page documents the portable file operations in Capy.
Code snippets assume using namespace boost::capy; is in effect.
|
file
A platform-independent file handle for reading and writing:
#include <boost/capy/file.hpp>
file f("data.txt", file_mode::read);
// Read data
std::vector<char> buf(1024);
std::size_t n = f.read(buf.data(), buf.size());
// Query file info
std::uint64_t sz = f.size();
std::uint64_t pos = f.pos();
// Seek to position
f.seek(100);
Construction
// Open on construction
file f("data.txt", file_mode::read);
// Default construct, then open
file f2;
f2.open("data.txt", file_mode::write);
Files automatically close when destroyed.
File Modes
| Mode | Access | Behavior |
|---|---|---|
|
Read-only |
Must exist, random access |
|
Read-only |
Must exist, sequential access |
|
Read/Write |
Create or truncate, random access |
|
Read/Write |
Must not exist, random access |
|
Read/Write |
Must exist, random access |
|
Write-only |
Create or truncate, sequential |
|
Write-only |
Must exist, sequential |
Reading
std::size_t n = f.read(buffer, size);
// Returns bytes read (0 on EOF)
Read operations advance the file position.
Writing
std::size_t n = f.write(data, size);
// Returns bytes written
Write operations advance the file position.
Seeking
f.seek(offset); // Seek to absolute position
std::uint64_t p = f.pos(); // Get current position
Seeking is available in random-access modes (read, write, write_new,
write_existing).
Error Handling
Platform Implementation
The file class automatically selects the best implementation:
-
Windows: Uses Win32 API (
CreateFile,ReadFile,WriteFile) -
POSIX: Uses POSIX API (
open,read,write) -
Fallback: Uses standard C library (
fopen,fread,fwrite)
All implementations provide the same interface.
Example: Copy File
void copy_file(char const* src, char const* dst)
{
file in(src, file_mode::read);
file out(dst, file_mode::write);
char buf[4096];
while (true)
{
std::size_t n = in.read(buf, sizeof(buf));
if (n == 0)
break;
out.write(buf, n);
}
}
Example: Append to Log
void log_message(char const* path, std::string_view msg)
{
file f(path, file_mode::append);
f.write(msg.data(), msg.size());
f.write("\n", 1);
}
Summary
| Class | Purpose |
|---|---|
|
Platform-independent file handle |
|
Open mode enumeration (read, write, append, etc.) |
Exception methods |
Throw on error |
Error code methods |
Return error via out parameter |
Next Steps
-
Containers — Type-erased containers
-
Brotli — High-ratio compression
-
ZLib — DEFLATE/gzip compression