Writing to files with file descriptors
We have already seen some uses of file descriptors in previous chapters, for example, 0, 1, and 2 (stdin, stdout, and stderr). But in this recipe, we will use file descriptors to write text to files from a program.
For this recipe, you only need what is listed under the Technical requirements section.
How to do it…
Here we will write a small program that writes text to a file:
- Write the following code in a file and save it as
fd-write.c. The program takes two arguments: a string and a filename. To write to a file using file descriptors, we must first open the file with the
open()system call. The
open()system call returns a file descriptor, which is an integer. We then use that file descriptor (the integer) with the
write()system call. We have already...