Linux programming open file

How to open the file in bash

The file is used to store the data permanently and use the data in any script when requires. A file can be opened for reading, writing, or appending. Many bash commands exist to open a file for reading or writing, such as `cat`, `less`, `more` etc. Any text editor can be used to open a file in bash. nano, vim, vi, etc., an editor is used to open a file from the terminal. Many GUI editors also exist in Linux to open a file, such as Gedit, Geany, etc. The file can be opened for reading or writing by using bash script also. The ways to open a file for various purposes have been shown in this tutorial.

Open file using Bash commands:

The uses of shell commands to open a file for creating or reading are shown in this tutorial. The uses of `cat`, `less`, and `more` commands have shown here.

Use of `cat` command:

The `cat` is a very useful command of bash to create or display the file’s content. Any file type can be created easily and quickly by opening the file using the `cat` command with the ‘>’ symbol. Run the following `cat` command to open a file named file1.txt for writing. If the filename already exists, then the previous content of the file will be overwritten by the new content; otherwise, a new file will be created.

Add the following content to the file.

A bash script is a command-line interpreted language.
Many automated tasks can be done easily using a bash script.

Press Ctrl+D to finish the writing task. The following output will appear after creating the file.

Now, run the following `cat` command to open the file.txt file for reading.

The following output will appear after executing the above command.

Use of `less` command:

The `less` command is used to open a file for reading only. It is mainly used to read the content of the large file. The user can move backward or forward through the file by using this command. It works faster than other text editors.

Run the following command to open the file1.txt file for reading. Here, the content of the file is very small. So when the user presses the enter key, then the content will go upward. Press the character ‘q’ to return to the command prompt.

The following output will appear after opening the file using the `less` command and pressing the enter key.

Use of `more` command:

Like the `less` command, the `more` command is used to open a large file for reading only. This command is mainly used to read a file’s large content in multiple pages to help the readers read long files.

Читайте также:  Winrar 64 bit linux

Run the following command to open the file1.txt file for reading by using the `more` command. It is a small file. So all content of the file has displayed on one page.

The following output will appear after opening the file using the `more` command.

Open file using command-line editors:

The uses of vi and nano command-line editors for opening the file to create and read have been shown in this part of this tutorial.

Use of vi editors:

One of the popular text editors of Linux is vi editors. It is installed on Ubuntu by default. The user can easily create, edit, and view any file by using this text editor. The advanced version of vi editors is called vim editor, which is not installed by default. This part of the tutorial shows how to use vi editor to open a file for creating and reading. Run the following command to open the file2.txt file for writing.

You have to press the character ‘i’ to start writing into the vi editor. Add the following content to the file.

Writing a file using vi editors.

You can do any of the following tasks after writing the content of the file.

  1. Type :wq to quit the editor after saving the file.
  2. Type :w to keep the file open in the editor after saving.
  3. Type :q to quit the editor without saving the file.

The following output shows that ‘:wq’ has been typed to quit the editor after saving the file.

Run the following command to open the file2.txt file and check the content exists or not that was added in the file.

The following output shows that the file contains the data that was added before. Here,’:’ has typed to quit the editor.

Use of nano editor:

Another useful and popular editor of Linux is the nano editor that is used to open a file for writing and reading. It is easier to use than the vi editor and more user-friendly than other command-line editors. Run the following command to open the file3.txt file for writing using nano editor.

Add the following content to the file.

Writing a file using nano editor.

If you type Ctrl+X after adding the content to the file, it will ask you to save the file. The following output will appear if you press the character, ‘y’. Now, press the enter to quit the editor after saving the file.

Open file using GUI text editor:

The ways to use gedit and geany GUI-based text editor have shown in the part of this tutorial.

Use of gedit editor:

The gedit is mostly used GUI-based text editor that is installed by default on maximum Linux distributions. Multiple files can be opened by using this editor. Run the following command the open the existing file1.txt file using gedit editor.

The following output will appear after executing the command.

Use of geany editor:

Geany is a more powerful GUI-based editor than the gedit editor, and you have to install it to use it. It can be used to write code for many types of programming languages. Run the following command to install the geany editor.

Читайте также:  Format disk linux ext4

After installing the editor, run the following command to open the file1.txt file.

The following output will appear after executing the command.

Conclusion:

Many ways to open a file for reading or writing have been shown in this tutorial by using bash command, command-line editors, and GUI-based editors. The Linux users can select any of the ways mention here to open a file in bash.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

Linux system programming: Open file, read file and write file

Terminal Prompt

This is my first article in what I’m hoping will be a series of articles on system programming for POSIX compliant operating systems with focus on Linux. Actually I’ve touched this topic a while ago when I wrote three articles about library programming on Linux (static libraries, dynamic libraries and dynamic libraries using POSIX API). In this series my goal is to go trough basics of Linux system programming from the easiest topics like open file, read file and file write to a bit more complicated things like Berkeley sockets network programming. So lets get started with environment setup and an example of program that copies source file into destination file using POSIX API system calls to demonstrate open(), read() and write() system calls on Linux operating system.

Configuring your environment

I’ll use my trustworthy Ubuntu Linux operating system but you can actually use any POSIX compliant operating system, the only difference will probably be that you will need to configure your environment differently. What we need to begin with Linux system programming is gcc compiler with related packages and POSIX related man pages. So here’s how to install this packages on Ubuntu based operating system:

sudo apt-get install build-essential manpages manpages-dev manpages-posix manpages-posix-dev

Basically that’s all you need to create serious system tools for Linux operating system. Later we will probably need some more libraries but we will install them when necessary.

open(), read() and write() system calls

Lets continue with our first system call open() whose purpose is to open file for reading or writing or to create new file. You should open it’s man page if you haven’t already done so using man 2 open command and read trough basics (2 is manual section number, use man man to read more about integrated manual section numbers). In the following example we also use read() and write() system calls to copy from one file descriptor to the other (both descriptors returned by open() system call) so it is wise to open their man pages as well ( man 2 read and man 2 write ). So here’s the example code for program that copies input file passed as first argument into output file passed as second argument:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
/* ============================================================================ Name : sp_linux_copy.c Author : Marko Martinović Description : Copy input file into output file ============================================================================ */ #include #include #include #include #include  #include #define BUF_SIZE 8192 int main(int argc, char* argv[]) { int input_fd, output_fd; /* Input and output file descriptors */ ssize_t ret_in, ret_out; /* Number of bytes returned by read() and write() */ char buffer[BUF_SIZE]; /* Character buffer */ /* Are src and dest file name arguments missing */ if(argc != 3){ printf ("Usage: cp file1 file2"); return 1; } /* Create input file descriptor */ input_fd = open (argv [1], O_RDONLY); if (input_fd == -1) { perror ("open"); return 2; } /* Create output file descriptor */ output_fd = open(argv[2], O_WRONLY | O_CREAT, 0644); if(output_fd == -1){ perror("open"); return 3; } /* Copy process */ while((ret_in = read (input_fd, &buffer, BUF_SIZE)) > 0){ ret_out = write (output_fd, &buffer, (ssize_t) ret_in); if(ret_out != ret_in){ /* Write error */ perror("write"); return 4; } } /* Close file descriptors */ close (input_fd); close (output_fd); return (EXIT_SUCCESS); }

If you have named this code file sp_linux_copy.c and if you want to name executable file sp_linux_copy to compile this program you would probably use something like this:

gcc -Wall -o sp_linux_copy sp_linux_copy.c

Then if your source file is named source_file.txt and if you want to name the destination file destination_file.txt you would run this program like this:

./sp_linux_copy source_file.txt destination_file.txt

Now lets go trough the code and explain tricky parts. First thing we must do is to include necessary header files. Man page of every system call tells you what header files you need to include to be able to use this system call. Second we will define constant we will use to define size of our buffer in bytes. Smaller buffer size will make our copy process longer but it will save memory. Next we open source and destination file descriptors, source with O_RDONLY to make it read only, destination with O_WRONLY | O_CREAT to make it writable and to create destination file with 0644 file system permission flags. In case of error we use perror() man 3 perror to print relatively user friendly error message.

Now we are ready to start copy process. We run read() and write() inside loop (because source file might be bigger than our buffer) to copy from one file into another. Important to notice is that write() is using number of bytes read from source file returned by read() so it would know how much to write into destination file. If number of bytes read (ret_in) and number of bytes written (ret_out) differ this indicates error so once again we use perror() to print out error description. At the end if all went well we do cleanup by closing both file descriptors and returning 0 (EXIT_SUCCESS) to indicate that program ended without errors.

That’s it for this introductory article on Linux system programming topic. In my next article I will show you few more examples on POSIX input/output and then move on to memory management related system calls.

Источник

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