One of C library functions I find most odd is dup(). I pronounce this function as if it rhymes with cup. I assume others may pronounce it like doop, which rhymes with poop. Whatever. The key is what the function does and how it could even remotely be necessary.
The dup() function works with the file descriptors returned when you use the “raw” open() function to work with file data, as reviewed in last week’s Lesson. The function duplicates a file descriptor, not the value but the reference to the open file. The result is that your code has two file descriptors, which seems weird but there is a point to it all, which I eventually get around to disclosing. In the meantime, here is the man page format:
int dup(int oldfd);
The oldfd argument represents an open file descriptor. The return value is a new file descriptor, assigned the lowest integer value available. The value -1 is returned should some sorta error happen.
The following code uses the dup() function to create two file descriptors, both of which access the same file:
2026_08_15-Lesson.c
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
int main()
{
char filename[] = "test.txt";
int fd1,fd2;
/* open/create the file */
fd1 = creat(filename,0);
if( fd1==-1 )
{
fprintf(stderr,"Unable to create %s\n",filename);
perror("ERROR: ");
exit(1);
}
/* duplicate the file descriptor */
fd2 = dup(fd1);
if( fd2==-1 )
{
fprintf(stderr,"Unable to duplicate the file handle\n");
perror("ERROR: ");
close(fd1);
exit(1);
}
/* write data to the file */
write(fd1,"Hello, ",7);
write(fd2,"world!\n",8);
/* clean-up */
close(fd2);
close(fd1);
return 0;
}
In this code, the creat() function opens/creates a file for writing only, truncating the file if it already exists:
fd1 = creat(filename,0);
Integer variable fd1 holds the creat() function’s return value, which is immediately tested for success. If the file was opened, the dup() function creates a duplicate file handle, saving it in int variable fd2:
fd2 = dup(fd1);
The function’s return value (fd2) is checked for an error. If no error is found, both file descriptors are used to write data to the file. First, fd1 is used:
write(fd1,"Hello, ",7);
Seven bytes are written to the file. The bytes represent the string "Hello, " plus one for the null character. Next, fd2 is used in the write() function to append text to the same file:
write(fd2,"world!\n",8);
As each file descriptor is open, two close() statements are necessary to wrap up the operation:
close(fd2);
close(fd1);
The program generates no output, but the test.txt file created has these contents:
Hello, world!
Though two file descriptors are used, the write() function sequentially sends the string data to the same file.
In next week’s Lesson, I continue to mess around with the duplicate file descriptors. Yes, there is a point to all this duplicate file descriptor nonsense, which I shall get to eventually.