Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade

How to Perform File I/O Operations in Linux

File I/O (Input/Output) operations are fundamental tasks in any operating system, and Linux is no exception. These operations allow users and applications to read from and write to files, which is essential for data storage, configuration management, and logging. In Linux, file I/O can be performed using a variety of tools and programming languages, such as shell scripting, Python, and C. This article will explore how to perform basic file I/O operations using shell commands and scripts, which are commonly used by Linux system administrators and developers.

Examples:

  1. Reading from a File: To read the contents of a file in Linux, you can use the cat, less, or more commands. Here is an example using cat:

    cat example.txt

    This command will display the contents of example.txt on the terminal.

  2. Writing to a File: To write data to a file, you can use the echo command along with output redirection (> or >>). Here is an example:

    echo "Hello, World!" > output.txt

    This command will write "Hello, World!" to output.txt, overwriting any existing content. To append data instead of overwriting, use >>:

    echo "Hello again!" >> output.txt
  3. Reading from a File in a Shell Script: You can read a file line by line in a shell script using a while loop. Here is an example script:

    #!/bin/bash
    
    while IFS= read -r line
    do
       echo "Line: $line"
    done < "example.txt"

    Save this script as readfile.sh, make it executable (chmod +x readfile.sh), and run it (./readfile.sh).

  4. Writing to a File in a Shell Script: You can write to a file within a shell script using the echo command. Here is an example script:

    #!/bin/bash
    
    echo "This is a test file." > output.txt
    echo "Appending another line." >> output.txt

    Save this script as writefile.sh, make it executable (chmod +x writefile.sh), and run it (./writefile.sh).

  5. Using dd for Low-Level File I/O: The dd command is used for low-level copying and conversion of raw data. Here is an example of creating a file with random data:

    dd if=/dev/urandom of=randomfile.bin bs=1M count=1

    This command creates a 1MB file named randomfile.bin filled with random data.

To share Download PDF

Gostou do artigo? Deixe sua avaliação!
Sua opinião é muito importante para nós. Clique em um dos botões abaixo para nos dizer o que achou deste conteúdo.