Programming techniques - OCRThe use of basic file handling operations

Proficient programming requires knowledge of many techniques. These techniques allow for powerful, complex programs.

Part ofComputer ScienceComputational thinking, algorithms and programming

The use of basic file handling operations

process and use . When the program finishes, or is closed, any data it held is lost. To prevent loss, data can be stored in a so that it can be accessed again at a later date.

Files have two modes of operation:

  • read from - the file is opened so that data can be read from it
  • write to - the file is opened so that data can be written to it

Each item of data written to or from a file is called a .

Opening and closing files

A file must be open before a record can be read from or written to it. To open a file, it must be referred to by its .

Example

file = openRead("scores.txt")

This would open the file scores.txt and allow its contents to be read.

file = openWrite("scores.txt")

This would open the file scores.txt and allow it to have data written to it.

file.close()

Reading from a file

Once a file has been opened, the records are read from it one line at a time. The data held in this record can be read into a , or, more commonly, an .

Example

file = openRead("scores.txt")
score = myFile.readLine()
file.close()

An array example is shown below.

file = openWrite("scores.txt")
for x = 0 to 9 scores[x]=myFile.readLine()
next x
file.close()

End of file

When reading a file that has more than one record, the computer needs to know what to do when there are no more records to read. The endOfFile() checks to see if the last record has already been read.

Example

file = openRead("scores.txt")
while NOT file.endOfFile() scores[x]=myFile.readLine() x = x + 1
endwhile
file.close()

The above code would read each record and place it into an array scores. The operation ceases when there are no more files to read.

Writing to file

Data is written to a file one line at a time, using the writeLine statement.

Example

file = openWrite("scores.txt")
for x = 0 to 9 file.writeLine(scores[x])
next x
file.close()

The above code would write the contents of an array scores to the file scores.txt.