Read from a file

READ(fileHandle, amount) returns data from a file as a string

Given a file handle this will read a certain amount of bytes from the file, specified by amount, and store the result as a string or an array of characters or even an array of bytes. The return type here will depend on the language used so for this just assume it is a string.

The READ method ALWAYS starts at position 0 of the file. When a file is opened a pointer is created which points to the start of the file or 0. Every call to read will move the pointer along by the amount requested. So if you call READ(file, 5) it would move the pointer by 5.

Look at the following example. The first row shows the position of each letter in the file and the second row shows the files contents at that position.

0

1

2

3

4

5

6

7

8

9

10

M

R

 

H

A

M

F

L

E

T

T

file = OPEN(“myDoc.txt”, R) a = READ(file, 2)
b = READ(file, 4)
c = READ(file, 3)
d = READ(file, 7)
CLOSE(file)

The contents of the variables a,b,c and d are –

a = “MR”
b = “ HAM” (note – position 2 is a space!)
c = “FLE”
d = “TT”

Each call to READ moves the file pointer by the amount specified. Consider the next example –

file = OPEN(“myDoc.txt”, R)
file2 = OPEN(“myDoc.txt”, R)
a = READ(file, 4) b = READ(file2, 4)
CLOSE(file)
CLOSE(file2)
a = “MR H”
b= “MR H”

Notice that both variables have the same value this time? This is because we have to file handles. Each file handle will have it’s own counter within it so reading using on handle will not affect the other.