= Filesystem API Tutorial = [[PageOutline(2-3)]] This tutorial will guide you through the steps that are necessary to work with files on the standard HelenOS API level in an idiomatic way. == Preparing to use the API == HelenOS filesystem API is implemented in the standard library, so there is no need to link against any additional library in order to access files. HelenOS requires you to only include `vfs/vfs.h` in order to get declarations of all filesystem APIs: {{{ #include }}} == Paths and File handles == The API is designed to use file handles as a primary way to refer to files. One may obtain a file handle by looking up a filesytem path, creating a new file or directory or attaching a new filesystem into the filesystem hierarchy. == Reading an existing file == Suppose we want to read the contents of file `/foo/bar`. We first need to lookup the file and convert it to a file handle: {{{ int file = vfs_lookup("/foo/bar", WALK_REGULAR); if (file < 0) return file; }}} This will only succeed if the file exists and is a regular file, i.e. not a directory, in which case `vfs_lookup()` receives a file handle. Otherwise we receive a negative error code and bail out. Because our intention is to perform a read operation on `file`, we must first open it for reading: {{{ int rc = vfs_open(file, MODE_READ); if (rc != EOK) { vfs_put(file); return rc; } }}} Note that `vfs_open()` does not take a path as an argument and does not return a file handle. Instead it takes a pre-existing file handle as an argument, internally marks the file as open for reading and returns a result code, which is EOK on success and negative on error. Also note that in case of error, the file handle we are using needs to be returned to the system before bailing out. We are now ready to do a couple of synchronous read from the file. Let's say we first want to read a 4KiB-buffer from offset 0x1000: {{{ uint8_t buffer[4096]; aoff64_t pos = 0x1000; ssize_t size = vfs_read(file, &pos, buffer, sizeof(buffer)); if (size < 0) { vfs_put(file); return size; } if (size == 0) { /* handle EOF */ } /* buffer is now guaranteed to contain the desired data */ ... }}} The position to read from was passed to `vfs_read()` explicitly. Moreover, `pos` was updated by `vfs_read()` to reflect the updated position. We are now ready to read an additional 4KiB-buffer from offset 0x2000: {{{ size = vfs_read(file, &pos, buffer, sizeof(buffer)); if (size < 0) { vfs_put(file); return size; } if (size == 0) { /* handle EOF */ } /* buffer is now guaranteed to contain the desired data */ ... }}} Finally, if we wanted to continue reading at offset 0x4000, we could simply do: {{{ pos = 0x4000; size = vfs_read(file, &pos, buffer, sizeof(buffer)); ... }}}