Explain basic file operations with example.


Q.) Explain basic file operations with example.

Subject: Data Structures - II

Basic File Operations

File operations are fundamental tasks that allow programs to interact with files and manipulate their contents. Here are some basic file operations along with examples:

  1. Creating a New File:
open(my $fh, '>', 'new_file.txt'); # Open file for writing
print $fh "Hello, world!";          # Write data to the file
close($fh);                        # Close the file
  1. Opening an Existing File:
open(my $fh, '<', 'existing_file.txt'); # Open file for reading
my $data = <$fh>;                    # Read data from the file (line by line)
close($fh);                        # Close the file
  1. Writing to a File:
open(my $fh, '>', 'new_file.txt'); # Open file for writing
print $fh "New data to be written."; # Write data to the file
close($fh);                        # Close the file
  1. Reading from a File:
open(my $fh, '<', 'existing_file.txt'); # Open file for reading
my $data = do { local $/; <$fh> };     # Read entire file into a variable
close($fh);                        # Close the file
  1. Seeking within a File:
open(my $fh, '>', 'existing_file.txt'); # Open file for writing
seek($fh, 10, 0);                    # Seek to the 11th byte
print $fh "Inserted data.";          # Write data at the specified position
close($fh);                        # Close the file
  1. Appending to a File:
open(my $fh, '>>', 'existing_file.txt'); # Open file for appending
print $fh "Appended data.";         # Append data to the end of the file
close($fh);                        # Close the file
  1. Truncating a File:
open(my $fh, '>', 'existing_file.txt'); # Open file for writing
truncate($fh, 0);                     # Truncate file to zero length
close($fh);                        # Close the file
  1. Renaming a File:
rename('old_file.txt', 'new_file.txt'); # Rename old_file.txt to new_file.txt
  1. Deleting a File:
unlink('existing_file.txt'); # Delete existing_file.txt
  1. Checking File Existence:
if (-e 'existing_file.txt') {
  print "File exists.\n";
} else {
  print "File does not exist.\n";
}
  1. Getting File Size:
my $filesize = -s 'existing_file.txt'; # Get file size in bytes
  1. Getting File Modification Time:
my $mtime = -M 'existing_file.txt'; # Get modification time in epoch time
  1. Setting File Permissions:
chmod 0755 'existing_file.txt'; # Set file permissions to 755

These are just some basic file operations that are commonly used in programming. There are various other advanced file operations and techniques that can be employed to perform more complex tasks.