programSequences of instructions for a computer. process and use dataUnits of information. In computing there can be different data types, including integers, characters and Boolean. Data is often acted on by instructions.. When the program finishes, or is closed, any data it held is lost. To prevent loss, data can be stored in a fileAnything you save. It could be a document, a piece of music, a collection of data or something else. 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 recordEach item of data written to or from a file..
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 identifierA name given to a part of a program, such as a variable, constant, function, procedure or module..
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 variableA memory location within a computer program where values are stored., or, more commonly, an arrayA set of data values of the same type, stored in a sequence in a computer program. Also known as a list. .
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()statementThe smallest element of a programming language which expresses an action to be carried out. 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.