#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

class File {
    int fd;                             /* always a valid descriptor */
    File(int d) : fd(d) {}              /* private: only Open creates */
    File(const File &);
    void operator=(const File &);
public:
    static File *Open(const char *name);
    ~File() { close(fd); }
    int Read(char *buf, int size) { return read(fd, buf, size); }
};

File *File::Open(const char *name)      /* can refuse: returns 0 */
{
    int d = open(name, O_RDONLY);

    if (d == -1)
        return 0;                       /* no object is created at all */
    return new File(d);
}

static void show_first_line(const char *name)
{
    File *f = File::Open(name);         /* no object needed to call it */
    char buf[80];
    int n, i;

    if (!f) {
        printf("%s: cannot open\n", name);
        return;
    }
    n = f->Read(buf, sizeof(buf));
    for (i = 0; i < n && buf[i] != '\n'; i++)
        ;
    printf("%s: %.*s\n", name, i, buf);
    delete f;
}

int main()
{
    show_first_line("/etc/hostname");
    show_first_line("/no/such/file");
    return 0;
}
