Skip to content

C++ class: File

Index · Français

Description

Noncopyable RAII owner of a newlib stdio stream.

Qualified name : gaspardos::File.

Header : bindings/cpp/gaspardos.hpp. C++98.

When to use it

Read or write a file using stdio conventions and errno.

Simple program example

#include "gaspardos.hpp"
#include <cstdio>
#include <cstring>

int main()
{
    gaspardos::File file;
    if (!file.open("/AHCIDISK0/readme.txt", "rb"))
        return 1;
    char        data[128];
    std::size_t count  = file.read(data, sizeof(data));
    int         failed = file.error();
    std::printf("%lu bytes\n", static_cast<unsigned long>(count));
    return file.close() == 0 && !failed ? 0 : 1;
}

Building from Windows

Save the program above as build/api-examples/File.cpp from the repository root. Create the directory if necessary.

PowerShell — from the repository root:

New-Item -ItemType Directory -Force build/api-examples | Out-Null
& .\build-x64-install\bin\x86_64-gaspardos-gcc.exe -std=gnu1x -O2 -mno-red-zone -c bindings/native/gaspardos_x64_syscall.c -o build/api-examples/syscall.o
if ($LASTEXITCODE -ne 0) { throw "C compilation failed" }
& .\build-x64-install\bin\x86_64-gaspardos-g++.exe -std=c++98 -O2 -Ibindings/cpp build/api-examples/File.cpp build/api-examples/syscall.o -o build/api-examples/File-x64.elf
if ($LASTEXITCODE -ne 0) { throw "C++ compilation/link failed" }

Run the ELF on GaspardOS, not Windows. The driver supplies CRT and libraries. Prepare the required volumes/services; examples bound their waits and may exit on backpressure rather than retry. Successful compilation does not validate kernel execution.

The headers, implementation files, native wrappers and complete examples are available under Source files.

Class methods

File()

Initialize a closed stream.

~File()

Try close once.

bool open(const char* path, const char* mode)

Open path using mode; false and errno on failure, EBUSY if already open.

int close()

Return 0 or EOF; release the pointer even if fclose fails. A second call does not retry.

std::size_t read(void* p, std::size_t n)

Return bytes read; zero can mean EOF or error. Check error().

std::size_t write(const void* p, std::size_t n)

Return bytes written; handle short writes and check close.

int seek(long offset, int origin)

Move using SEEK_SET/CUR/END; return the fseek result.

int error() const

Return the stream ferror indicator, or EBADF when closed; this is not errno.

Native contract

LP64 ABI, 32-bit wchar_t, no packing. Native negative results are not errno. Handle -11 with yield and an application limit. Referenced objects must outlive their users; do not copy handle owners. File uses stdio/errno and invalidates its stream on close, even on error.