Files - PowerPoint PPT Presentation

1 / 11
About This Presentation
Title:

Files

Description:

Open/close File. close (filehandle) or die $!; mode: Input (default) (READ MODE) ... close (RESULTS) or die 'Error - $!'; Reading and Writing Files ... – PowerPoint PPT presentation

Number of Views:19
Avg rating:3.0/5.0
Slides: 12
Provided by: csUt8
Category:
Tags: close | files

less

Transcript and Presenter's Notes

Title: Files


1
Files
2
File Overview
  • A file is a sequence of bytes stored on disk.
  • Provides a means of stable store.
  • Perl has 3 predefined files
  • One for keyboard input.
  • One for screen output.
  • One for error messages.
  • Most languages and systems originating in the
    Unix environment have these.

3
Filehandles
  • Files are referenced through special variables
    called filehandles.
  • A filehandle is a variable that we associate with
    an actual file.
  • By convention, filehandles are all uppercase
  • Avoid name conflicts with reserved words.
  • e.g. STDIN, STDOUT, STDERR.

4
Open/close File
5
Open file (example)
6
Open Failures
  • open can fail for several reasons
  • File for input does not exist.
  • No more filehandles.
  • open returns true if it succeeds.
  • Can check why open fails with die.
  • open (INDAT, score) or die Error !
  • ! contains error message from the system.

7
Close
  • Some programmers prefer to explicitly close a
    file.
  • Closing a file can fail too
  • Not enough disk space.
  • The function call is
  • close (filehandle)
  • Can detect cause of failure with
  • close (RESULTS) or die Error - !

8
Reading and Writing Files
  • We have read and written to files before
  • Read lines from the keyboard and written to
    screen.
  • Reading a line from a file is similar
  • ltfilehandlegt
  • Writing a line to a file is easy too
  • print filehandle OUTPUT

9
An Example
  • !/usr/bin/perl -w
  • Open the files.
  • source shift _at_ARGV
  • destination shift _at_ARGV
  • open (IN, lt, source) or die Cant read source
    file source !\n
  • open (OUT, gt, destination)
  • or die Cant write to file destination
    !\n
  • Read until EOF.
  • print Copying source to destination\n
  • while (ltINgt)
  • print OUT
  • Close the filehandles.
  • close (IN)
  • close (OUT)

10
File Tests
  • Sometimes, a program needs to know information
    about a file before using it.
  • (EX) Does a file with the same name exists?
  • File tests are unary operators.
  • Operand is an expression that evaluates to a
    string.
  • String must be a file or filehandle.

11
File Tests (cont.)
  • -e True if file exists.
  • -r True if file is readable.
  • -w True if file is writeable.
  • -x True if file is executable.
  • -d True if file is a directory.
  • -f True if file is a regular file.
  • -T True if file is a text file.
  • -B True if file is a binary file.
  • -s Length of file in bytes.
  • -z True if its zero size
Write a Comment
User Comments (0)
About PowerShow.com