Linux gcc open file

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
#include
#include
int main ( )
int f = open ( «new.txt» , O_RDONLY

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”.

Читайте также:  Android sdk linux and

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
#include
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

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.

Источник

How Do You Write to a File in C?

You must have heard about file handling while working in the C language. This is a concept widely known among C developers and programmers. It is a simple and easy concept of creating a file, opening a file, reading and writing into the file, and closing it. The C language uses different built-in methods to achieve all these functionalities.

Today, we will learn about writing to a file in C language with different built-in functions of file handling while working on the Ubuntu 20.04 Linux system. Start the Linux terminal first using the “Ctrl+Alt+T” shortcut.

Example 01: Using fprintf() Method

We will start our first example by creating a new C file in the Linux system. Thus, the “touch” query will be used for that. The filename has been given as “file.c”. After the creation of a file, we need to open it to write some C code in it. This requires some editor to be installed on your system. There are several editors available in Linux. We are using the “GNU Nano” editor here. So, the “nano” keyword in the command shows the usage of Nano editor to edit the C file.

We have to add the standard libraries of the C language. The very well-known and always required library is a standard input-output header which is added in our code with the “#include” keyword at the top of a file. Start the initialization of a “main” method. Within the main() method, you need to first create a file descriptor i.e. file object. This descriptor will be used to open, close, read, write the file and must be a pointer type.

Читайте также:  Обновление арч линукс через терминал

We have used this file object descriptor to open the file with the use of the “open()” method widely known in the concept of filing in C language. This method takes two arguments in its parameters. The first one is “path” to the file and the other is “mode” in which the file will be opened. Point to be noted that within the Linux environment, you don’t need to create a new file to add data into it.

In Linux, you can simply put up the name within the path parameter of the “open()” method and your file will be automatically generated at the specified location. We have added “w+” mode to let the user write and edit the file.

Now, the main point came. The “fprintf” clause has been used here to write data in the file “new.txt” with the help of its descriptor “f”. After writing in the file, you need to close the file descriptor to quit letting a user do more, with the usage of the “close()” function here. The main method will be ended here. Save this code and quit the editor by utilizing “Ctrl+S” and “Ctrl+X”.

To execute the C code, we need to compile it first. If you don’t have a C compiler in your Linux system, try to get “gcc”. So, we have used the “gcc” command along with the name of a file “file.c” to compile the code within it. If the compilation doesn’t return anything, this means your code is error-free.

We have executed it with the “./a.out” command. The execution also didn’t return anything. Now, check the file that has been created by this code i.e. “new.txt” with the “cat” query. You will see that the data is successfully written into the file.

Example 02: Using fputc() Method

This function is known for writing a single character within the file at a time. Let’s begin to see how it works. Open the same C file to make it up to date. After adding the header input-output library, initialize the main() method. Within the main method, add the pointer type file descriptor. This file descriptor is opening the file “new.txt” with the “fopen()” function of C.

The syntax is the same as per the above example. The only required to change is the “fputc” function here is taking two arguments. One is the data i.e., character and the other is the file descriptor to specify the file. After adding the data into a file, the descriptor is used to close the file with the “fclose()” method.

Compile the file first and execute it after that. Nothing happens because the code was correct. Display the data of a “new.txt” file in the shell with the use of the “cat” command. The old data has been replaced by the character “A”.

Читайте также:  Open pdf linux console

Example 03: Using fputs() Method

Within this example, we will be using another function i.e. “fputs” to write data into a text file. The fputs() function differs from the “fputc()” function because it takes string-type values instead of a character. There is no need to alter the overall code. The only change is required at the “fputs()” function line. Replace “fputc” with “fputs”.

We have to change the data that will be written into the file as well. Within both fputc() and fputs() methods, the argument descriptor pointer is used after the “string” while in the “fprintf” it is used first. Save your file to get it updated.

Let’s compile and execute the code once again with “gcc” and “a.out” commands. We got successful as the data is successfully written into the file “new.txt”.

Example 04:

Let’s have a little enhanced example. After opening the same “file.c” file, add the input-output and standard library header at the top. After that, the main method is started with the “int” return type. A character type array variable “Arr” has been declared having size 1000. The file descriptor of pointer type has been declared i.e., “f”. The file “new.txt” has been opened with the “fopen()” function of file handling with the usage of file descriptor “f”. The write mode has been used to open and write into the file.

Here comes the “if” statement. It will check if the file descriptor has not been bonded with any file and is empty, it will print that there is some error and the program will stop executing further. If the descriptor would be successfully open and create the file, the user will be asked to enter some data at the shell terminal via the “printf” clause. The “fgets()” function is a new concept here.

It is used to get the standard input entered by a user, check its size, and save it into a character variable “Arr”. The “fprintf” method is used to input this “Arr” variable into the file with its descriptor. The file descriptor gets close here.

The output is quite expected. The user has entered some sentences and the file has been displayed with the data in it.

Conclusion

Within this guide today, we have discussed the ways to write data into a file while working on C language. We have used different file handling built-in functions of C to do so i.e., fopen, fputc, fputs, fprintf, fgets, and fclose. On the other hand, the concept of pointers and arrays has been used as well. We extremely believe this article contains all the necessary illustrations required to understand the file writing concept in C language.

About the author

Aqsa Yasin

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.

Источник

Оцените статью
Adblock
detector