C Programming

POSIX Open Function in C

Although there are a lot of libraries in C, the POSIX library is very well-known among the developers due to its wide range of system call functions, especially the system function calls for “files”. POSIX library for Linux operating system provides you with a variety of functions. There is an open() function that is purposely used to open a specific file from a system in one of those POSIX calls. It utilizes many options to create, open, read, write, and do many things on the Linux files.

Example 1:
Let’s take a look at the first example to use the open() function of POSIX to simply create and open the files in a read-only mode. For this, use the touch query in your shell to create a C file. It can be saved into the current working folder.

Open your newly generated file, i.e. open.c, in the editor to add some code snippet within it just like in the presented image. Start your code with the use of C standard headers like stdio.h, fcntl.h, and errno.h that are purposely included for standard input/output, use of filing, and display the errors, respectively. There is a main() function to perform the execution. We create an integer variable “f” that is used as a file descriptor to get the returned value from the “open()” function call. The open() function uses the text file name along with two options – the “O_RDONLY” option to read the already existing file and the “O_CREAT” option to create a file if it does not exist.

The printf() statement displays the returned value using the descriptor “f”. The value of “f” is equal to “-1”. It throws an error that we failed to open or create a file along with an error message via the perror() function. Otherwise, the printf() statement displays the success message on our screen. The code is completed using the return 0 statement.

#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
int main() {
  int f = open("new.txt", O_RDONLY | O_CREAT);
  printf("file descriptor value = %d\n", f);
  if(f == -1) {
     perror("Failed to create/open a file...\n);  }
  else {
     printf("
File created successfully!\n"); }
  return 0;
}

After the code is saved successfully, we compile it with the command-line “gcc” tool like the C compiler that is available in the Linux system. Write the keyword “gcc” with the name of a file “open.c” and run it. The compilation is prosperous, and we try the “./a.out” query to run the compiled code. The output shows the value of “f” along with a success message that indicates that we finally created a new text file successfully. The “ls” instruction output shows the red highlighted “new.txt” file created by the open() function’s “O_CREAT” option in the current working folder.

Let’s utilize the same code to get an error if the open() function finds itself unable to read a file that is not existing in the system. Using the same structure of the code, we update the main() function’s first line of code. Here, we remove the “O_CREAT” option to create a new file using the open() function call and only use the “O_RDONLY” option.

Also, we change the name of a file to “test.txt” which doesn’t exist in our working folder. This means that the open() function is unable to open the file and the perror() function displays the respective error message at the console. Let’s save this updated C file.

#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
int main() {
  int f = open("test.txt", O_RDONLY);
  printf("file descriptor value = %d\n", f);
  if(f == -1) {
     perror("Error: [Failed to Open a file] : );  }
  else {
     printf("
File Opened successfully!\n"); }
  return 0;
}

Running the file after execution throws the “No such file or directory” error.

Example 2:
You can use the open() function call to read a string data from a specific file using the arrays. For that, you just need the “unistd.h” and “fcntl.h” libraries. The code execution starts from its primary “main()” method that declares a character type array “A” of size 30. The integer file descriptor uses the returned value from the open() function call. The open() function that is used here casts off its “O_RDONLY” option to open it in the read-only mode. The read() function at the very next line is used to store a total of 12 characters from the “file.txt” using its descriptor “f” and save it to the character array “A”.

If the read() function is successful to read data from a file, it returns some value to the variable “n”. The write() function call uses the variable “n” to write the data on the console that is just saved to the array “A”.

#include <unistd.h>
#include <fcntl.h>
int main() {
  char A[30];
  int f = open("file.txt", O_RDONLY);
  int n = read(f, A, 12);
  write(1, A, n);
}

Now, we need to create the same name text file “file.txt” in the same folder and add some text data into it as presented using the “Cat” instruction of Linux. We compile and execute our “open.c” file and get the first 12 characters from the “file.txt” are displayed on the shell.

Example 3:
You can use the open() function call to copy the text data from one file to another with a slight change in the code. We cast off the same example code snippet and make some changes to a few of its lines. The size of character buffer “A” is updated to 50 and the f1 descriptor opens the file “file.txt” in a “read-only” mode using the “O_RDONLY” in an open() function. The read() function uses the “f1” descriptor to read 25 characters from the “file.txt” file and save them to buffer array “A”. The returned success/failure value is saved to variable “n”.

Another file descriptor “f2” is used here to create a new file named “source.txt” within the same folder using the “0_CREAT” option in an “open” method and with a “write-only” mode (O_WRONLY) with the 0642 value to write. The write() function call uses the value “n” to get the data from the character buffer “A” and parse it to the second file “source.txt” using its descriptor “f2”. Now, let’s run the following code to see what we get in the output:

#include <unistd.h>
#include <fcntl.h>
int main() {
  char A[50];
  int f1 = open("file.txt", O_RDONLY);
  int n = read(f1, A, 25);
  int f2 = open("source.txt", O_CREAT | O_WRONLY, 0642)
  write(f2, A, n);
}

Now, we have a “file.txt” and “open.c” file in the current folder. You can see the data within the “file.txt”. In the “open.c” file execution, the source.txt file is generated and the 25 characters from the “file.txt” file are copied to the “source.txt” file as well.

Conclusion

This guide is simple yet full of C examples to utilize and learn the POSIX “open()” function call. Using all the given examples, you will never fail while using the files in C.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content