FILE OPERATIONS

  • Opening files
  • Reading from a file
  • Writing to a file
  • Appending a file
  • Closing a file
  • Detecting EOF (End of File)

PSEUDOCODE FOR FILE OPERATIONS:

OPENING A FILE

Open the file “Students.txt” in READ mode.

OPEN FILE "Students.txt" FOR READ

Open a file ‘Names.txt’ in WRITE mode.

OPEN FILE "Names.txt" FOR WRITE

Open the file ‘Names.txt‘ for Append.

OPEN FILE "Names.txt" FOR APPEND

Read a line from a file to a variable called ‘text‘.

READ FILE "Names.txt", text

Example #1

Write pseudocode for reading the content of the file named Nameless.txt and display the content on screen.

DECLARE MyFile : STRING
DECLARE Line: STRING

MyFile ← "Nameless.txt"
OPENFILE MyFile FOR READ
WHILE NOT EOF(MyFile) DO
READFILE MyFile, Line
OUTPUT Line
ENDWHILE
CLOSEFILE MyFile

Example #2

Write pseudocode to transfer all the content of the file “Candidates.txt” to “Finalist.txt”

DECLARE Source: STRING
DECLARE Target: STRING
DECLARE Line: STRING

Source ← "Candidates.txt"
Target ← "Finalist.txt"
OPENFILE Source FOR READ
OPENFILE Target FOR WRITE

WHILE NOT EOF(Source) DO
READFILE Source, Line
WRITEFIILE Target, Line
ENDWHILE
CLOSEFILE Source
CLOSEFILE Target

Problem #

A file contains details of students. Each line stores details of one student like ID, Name, Class and Address.

Write pseudocode to transfer the details of all the students who are from 12A to a new file called newrecord.txt. All fields are sorted as fixed-length fields as follows.

<ID><Name><Class><Address>

ID – 4 characters

Name – 20 characters

Class – 3 characters

Address – 3 characters

Solution:

DECLARE SourceFile : STRING
DECLARE TargetFile : STRING
DECLARE Line, Class : STRING

SourceFile = "Students.txt"
TargetFile = "NewFile.txt"

OPENFILE SourceFile FOR READ
OPENFILE TargetFile FOR WRITE

WHILE NOT EOF(SourceFile)
READFILE SourceFile, Line
Class ← MID(Line, 20, 3)
IF Class = "12A" THEN
WRITEFILE TargetFile, Line
ENDIF
ENDWHILE

CLOSEFILE SourceFile
CLOSEFILE TargetFile