Linux Program to Read from a File using File Descriptors

«
»
This Linux Program illustrates Reading from a File using File Descriptors.

Here is the source code of Linux Program to Read from 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 Read from a File using File Descriptors.
  3. */
  4.  
  5. #include <stdio.h>
  6. #include <sys/types.h>
  7. #include <sys/stat.h>
  8. #include <fcntl.h>
  9. #include <unistd.h>
  10. #include <errno.h>
  11. #include <stdlib.h>
  12.  
  13. int main(int argc, char **argv)
  14. {
  15.     int fd,retval;
  16.     char *buffer;    
  17.  
  18.     if (argc < 2) {
  19.         printf("Usage : %s pathname\n", argv[0]);
  20.         exit(1);
  21.     }
  22.  
  23.     /*opening the file in read-only mode*/
  24.     if ((fd = open(argv[1], O_RDONLY)) < 0) {
  25.         perror("Problem in opening the file");
  26.         exit(1);
  27.     }
  28.  
  29.     /*reading bytes from the fd and writing it to the buffer*/
  30.     while ((retval = read(fd, buffer, 1)) > 0)
  31.         printf("%c", *buffer);    
  32.     if (retval < 0) {
  33.         perror("\nRead failure");
  34.         exit(1);
  35.     }
  36.     printf("\nSuccessfully read bytes from the file %s\n", argv[1]);
  37.  
  38.     close(fd);
  39. }

$ echo "hello san" > my_file
$ gcc read_file.c
$ ./a.out my_file
 
hello san 
Successfully read bytes from the file my_file

Sanfoundry Global Education & Learning Series – 1000 Linux Programs.

Note: Join free Sanfoundry classes at Telegram or Youtube
advertisement
advertisement
If you wish to look at all Linux Programming examples, go to Linux Programs.

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 & technical discussions at Telegram SanfoundryClasses.