File system

File system open

#include <fcntl.h>

int open(const char* pathname, int flags, ... /* arg */)

int fd = open("/FileSystemTest/test1.txt", O_RDWR | O_CREAT | O_TRUNC);
if (fd != -1) {
    for(int ii = 0; ii < 100; ii++) {
        String msg = String::format("testing %d\n", ii);

        write(fd, msg.c_str(), msg.length());

Open a file for reading or writing, depending on the flags.

  • pathname: The pathname to the file (Unix-style, with forward slash as the directory separator).
  • flags: These flags specify the read or write mode:

    • O_RDWR: Read or write.
    • O_RDONLY: Read only.
    • O_WRONLY: Write only.

    These optional flags can be logically ORed with the read/write mode:

    • O_CREAT: The file is created if it does not exist (see also O_EXCL).
    • O_EXCL: If O_CREAT | O_EXCL are set, then the file is created if it does not exist, but returns -1 and sets errno to EEXIST if file already exists.
    • O_TRUNC If the file exists and is opened in mode O_RDWR or O_WRONLY it is truncated to zero length.
    • O_APPEND: The file offset is set to the end of the file prior to each write.

Returns: A file descriptor number (>= 3) or -1 if an error occurs.

On error, returns -1 and sets errno. Some possible errno values include:

  • EINVAL Pathname was NULL, invalid flags.
  • ENOMEM Out of memory.
  • EEXIST File already exists when using O_CREAT | O_EXCL.

When you are done accessing a file, be sure to call close on the file descriptor.

Opening the same path again without closing opens up a new file descriptor each time, as is the case in UNIX.