System Calls for File Operations in Unix/Linux: open-close-lseek System Calls

open : open a file for READ, WRITE, APPEND

int open(char *file, int flags, int mode);

close : close an opened file descriptor

int close(int fd);

read : read from an opened file descriptor

int read(int fd, char buf[ ], int count);

write : write to an opened file descriptor

int write(int fd, char buf[ ], int count);

lseek : reposition the byte offset of a file descriptor to offset from whence

int lseek(int fd, int offset, int whence);

umask: set file creation mask; file permissions will be (mask & ~umask)

1. Open File and File Descriptor

#include <sys/type.h>

#include <sys/stat.h>

#include <fcntl.h>

int open(char *pathname, int flags, mode_t mode)

Open() opens a file for READ, WRITE or APPEND. It returns a file descriptor, which is the lowest available file descriptor number of the process, for use in subsequent read(), write(), lseek() and close() syscalls. The flags field must include one of the following access mode O_RDONLY, O_WRONLY, or O_RDWR. In addition, flags may be bit-wise ORed with other flags O_CREAT, O_APPEND, O_TRUNC, O_CLOEXEC, etc. All these symbolic constants are defined in the fcntl.h header file. The optional mode field specifies the permissions of the file in Octal. The permissions of a newly created file or directory are the specified permissions bit-wise ANDed with ~umask, where umask is set in the login profile as (octal) 022, which amounts to deleting the w (write) permission bits for non-owners. The umask can be changed by the umask() syscall. Creat() is equivalent to open() with flags equal to O_CREAT|O_WRONLY|O_TRUNC, which creates a file if it does not exist, opens it for write and truncates the file size to zero.

2. Close File Descriptor

#include <unistd.h>

int close(inf fd);

Close() closes the specified file descriptor fd, which can be reused to open another file.

3. Iseek File Descriptor

#include <sys/type.h>

#include <unistd.h>

off_t lseek(int fd, off_t offset, int whence);

In Linux, off_t is defined as u64. When a file is opened for read or write, its RW-pointer is initialized to 0, so that read|write starts from the beginning of the file. After each read |write of n bytes, the RW-pointer is advanced by n bytes for the next read|write. lssek() repositions the RW-pointer to the specified offset, allowing the next read|write from the specified byte position. The whence parameter specifies SEEK_SET (from file beginning), SEEK_CUR (current RW-pointer plus offset) SEEK_END (file size plus offset).

Source: Wang K.C. (2018), Systems Programming in Unix/Linux, Springer; 1st ed. 2018 edition.

Leave a Reply

Your email address will not be published. Required fields are marked *