open() & read()
Last updated
Was this helpful?
Last updated
Was this helpful?
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:
For the function to work, you must first implement the following library
This function will allow you to open and access a file. It is prototyped this way:
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 β/β
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.
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.
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.
The function is prototyped this way:
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