Linux Program to Append a File Atomically with File Descriptors

This Linux Program illustrates Appending a File Atomically Using File Descriptors.

Here is the source code of Linux Program to Append a File Atomically Using File Descriptors. The Linux Program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2. * Linux Program to Append a File Atomically
  3. * Using File Descriptors.
  4. */
  5.  
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <unistd.h>
  9. #include <sys/types.h>
  10. #include <sys/stat.h>
  11. #include <fcntl.h>
  12. #include <string.h>
  13.  
  14. int main(int argc, char **argv)
  15. {
  16.     int fd;
  17.     char buf[20];
  18.     size_t nbytes;
  19.     ssize_t bytes_written;
  20.  
  21.     if (argc < 2) {
  22.         printf("Usage : %s pathname\n", argv[0]);
  23.         exit(1);
  24.     }
  25.  
  26.     strcpy(buf, "This is a atomic test\n");
  27.     nbytes = strlen(buf);
  28.  
  29.     /* opening the file in append mode */
  30.     if ((fd = open(argv[1], O_WRONLY | O_APPEND)) < 0) {
  31.         perror("Problem in opening the file in append mode");
  32.         exit(1);
  33.     }
  34.  
  35.     /* writing to the file - pwrite for atomic write */
  36.     if ((bytes_written = pwrite(fd, buf, nbytes, 0)) < 0) {
  37.     	perror("Problem in writing to file");
  38.     	exit(1);
  39.     }
  40.     printf("Successfully written to %s\n", argv[1]);
  41.  
  42.     close(fd);
  43. }

 
$ gcc atomic_append_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]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.