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.
Knowing how to use file descriptors to write to files both gives you a deeper understanding of the system and enables you to do some low-level stuff.
Getting ready
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 theopen()
system call. Theopen()
system call returns a file descriptor, which is an integer. We then use that file descriptor (the integer) with thewrite()
system call. We have already...