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.
/*
* Linux Program to Read from a File using File Descriptors.
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int fd,retval;
char *buffer;
if (argc < 2) {
printf("Usage : %s pathname\n", argv[0]);
exit(1);
}
/*opening the file in read-only mode*/
if ((fd = open(argv[1], O_RDONLY)) < 0) {
perror("Problem in opening the file");
exit(1);
}
/*reading bytes from the fd and writing it to the buffer*/
while ((retval = read(fd, buffer, 1)) > 0)
printf("%c", *buffer);
if (retval < 0) {
perror("\nRead failure");
exit(1);
}
printf("\nSuccessfully read bytes from the file %s\n", argv[1]);
close(fd);
}
$ 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.
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:
- Practice Programming MCQs
- Check Linux Books
- Apply for Programming Internship
- Check Information Technology Books