This Linux Program illustrates Appending to the End of a File using File Descriptors.
Here is the source code of Linux Program to Append to the End of a File Using File Descriptors. The Linux Program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* Linux Program to Append to the End of a File using File Descriptors.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
int main(int argc, char **argv)
{
int fd;
char buf[20];
size_t nbytes;
ssize_t bytes_written;
if (argc < 2) {
printf("Usage : %s pathname\n", argv[0]);
exit(1);
}
strcpy(buf, "This is a test\n");
nbytes = strlen(buf);
/* opening the file in append mode */
if ((fd = open(argv[1], O_WRONLY | O_APPEND)) < 0) {
perror("Problem in opening the file in append mode");
exit(1);
}
/* writing to the file */
if ((bytes_written = write(fd, buf, nbytes)) < 0) {
perror("Problem in writing to file");
exit(1);
}
printf("Successfully written to %s\n", argv[1]);
close(fd);
}
$ gcc append_to_file.c
$ a.out my_file
Successfully written to my_file
Sanfoundry Global Education & Learning Series – 1000 Linux Programs.
advertisement
advertisement
If you wish to look at all Linux Programming examples, go to Linux Programs.
If you find any mistake above, kindly email to [email protected]Related Posts:
- Check Information Technology Books
- Check Linux Books
- Apply for Programming Internship
- Practice Programming MCQs