β–ͺ️open() & read()

To start this project you must first be able to open a text file. Once opened, we will be able to read it. This can be done using the open() and read() functions.

PS: If you don't know what it is is a file descriptor (fd), you can check this page before continuing:

πŸ—ƒοΈpageFile descriptors (FD)

open ()

For the function to work, you must first implement the following library

#include <fcntl.h>

This function will allow you to open and access a file. It is prototyped this way:

int open (const char* path, int flags [, int mode ]);

Path

It corresponds to title of the file that you would like to open/create.

It also refers to the file’s location. If you are not working in the same directory as the file, you can provide an absolute path that begins with β€œ/”

Flags

You have to tell your function what kind of access you want. This is done with flags. Here is the list with the information of each flag:

  • O_RDONLY: In read-only mode, open the file.

  • O_WRONLY: In a write-only mode, open the file

  • O_RDWR: Open the file in reading and write mode

  • O_CREAT: This flag is applied to create a file if it doesn’t exist in the specified path or directory

  • O_EXCL: Prevents the file creation if it already exists in the directory or location.

Return Value

The return value of open() is a file descriptor, a small, nonnegative integer that is an index to an entry in the process's table of open file descriptors. If there is an error somewhere, the function will return -1 as a synonym of failure.

Example

There has to be a text.txt file so you can open it.

int main()
{
    int fd;
    fd = open("text.txt", O_RDONLY);
}

For the moment it will not show you anything because the function is only used to open a file. You will have to use an additional function to make it useful. For example the read() function that we will see together now.

read ()

The function is prototyped this way:

ssize_t read(int fildes, void *buf, size_t nbyte);

This function attempts to read nbyte bytes of data from the object referenced by the descriptor fildes into the buffer pointed to by buf. The read() function starts at a position given by the pointer associated with fildes. At the end, the pointer is incremented by the number of bytes (nbyte) actually read.

It is well explained in the below video, so I will not get through it once again:

It is in french but it has english subtitles !

Now that you know how these two functions work, let's move on to the next step: understanding static variables. A concept that will be used a lot in other projects! See you there πŸ˜„

Last updated