This Linux Program illustrates Opening and Closing a File using File Descriptors. We will going to use open() system call to open the file that takes two arguments. First argument is the file-name and second must include one of the O_RDONLY, O_WRONLY, or O_RDWR. O_RDONLY indicates open the file in read-only mode, with this mode user would not be able to write to file. O_WRONLY indicates open the file in write-only mode, with this mode user would not be able to read from the file. O_RDWR indicates open the file in both read and write mode. In this example, we are going to use O_RDWR mode. The open() system call returns an integer value, which is called the file descriptor and it is uniquely associated with each file that we opens. File descriptor can further be used to perform read, write and close operations. Now, to close the file we use close() system call that takes the file descriptor of the file that we would like to close.
Here is the source code of Linux Program to Open and Close 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 Open and Close a File using File Descriptors.
*/
#include
#include
#include
#include
#include
#include
int main(int argc, char **argv)
{
int fd;
if (argc = 0 ) {
printf("File %s opened successfully.\n", argv[1]);
} else {
perror("Problem in opening the file");
exit(1);
}
printf("Time to close the opened file %s.\n", argv[1]);
/* closing the opened file */
close(fd);
}
$ gcc open_close_file.c $ ./a.out my_file This example would give error if the file does not exist and need to first create a new file. In this example we are assuming that the file already exist and we will see the output, File my_file opened successfully. Time to close the opened 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.
Related Posts:
- Apply for Programming Internship
- Check Information Technology Books
- Check Linux Books
- Practice Programming MCQs