Linux Program to Write to a File using File Descriptors

This Linux Program illustrates Writing to a File using File Descriptors.

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

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

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.