When we run the cat sample.txt
command, we see that initially, the sample.txt
file is empty.
After running the program via the ./main
command, we again print the contents of the sample.txt
file. Now we see that it contains the data in the buffer variable.
Code explanation
Line 9: We make a character pointer and initialize it with the file name we want to open.
Line 11: We open the file via the open()
command in read and write mode specified by the second argument O_RDWR
.
Lines 13–19: Here, we check if the file opened correctly. If it does not, we exit the program with an exit status of 1
.
Line 21: We make a character pointer named buffer
and initialize it with the contents we want to write to the file.
Line 23: We call the write()
function to write the buffer
contents to the file sample.txt
. We pass three arguments: the file descriptor fd
, the char array buffer
, and the maximum number of bytes to write strlen(buffer)
. The function will return the number of bytes it wrote into the file, which we store in an integer variable bytesWritten
.
Line 25: Now, we will print the number of bytes that were written to the sample.txt
file.
Coding exercise on using the write()
function
Now that we understand how to write data to a file using the write()
function, let's test ourselves by completing the following code.
In the code file below, we have a buffer
object initialized with the string You are stronger than you think
and we have an empty text file named file.txt
.
Our task is to write 16 characters from the buffer to the file.
Complete the write()
function below to write You are stronger
into the file, which entails the first 16 bytes of the buffer.