#include <iostream>
#include <ext/stdio_filebuf.h>
#include <fcntl.h>
#include <unistd.h>

int main() {
    int fd = open("example.txt", O_WRONLY | O_CREAT | O_APPEND, 0666);
    if (fd == -1) {
        perror("open");
        return 1;
    }

    // Lock setup
    struct flock lock{};
    lock.l_type = F_WRLCK;
    lock.l_whence = SEEK_SET;
    lock.l_start = 0;
    lock.l_len = 0;

    if (fcntl(fd, F_SETLKW, &lock) == -1) {
        perror("fcntl");
        return 1;
    }

    std::cout << "File locked\n";

    // THIS is the correct bridge
    __gnu_cxx::stdio_filebuf<char> buf(fd, std::ios::out);
    std::ostream out(&buf);

    out << "Hello using << with locking!" << std::endl;
    out.flush();

    std::cout << "Press Enter to unlock...\n";
    std::cin.get();

    // Unlock
    lock.l_type = F_UNLCK;
    fcntl(fd, F_SETLK, &lock);

    close(fd);
    return 0;
}
