Presentation is loading. Please wait.

Presentation is loading. Please wait.

Programming Techniques :: File Handling

Similar presentations


Presentation on theme: "Programming Techniques :: File Handling"— Presentation transcript:

1 Programming Techniques :: File Handling
Last modified: 4th June 2019

2 www.drfrostmaths.com ? Everything is completely free.
Why not register? Registering on the DrFrostMaths platform allows you to save all the code and progress in the various Computer Science mini-tasks. It also gives you access to the maths platform allowing you to practise GCSE and A Level questions from Edexcel, OCR and AQA. With Computer Science questions by: Your code on any mini-tasks will be preserved. Note: The Tiffin/DFM Computer Science course uses JavaScript as its core language. Most code examples are therefore in JavaScript. Using these slides: Green question boxes can be clicked while in Presentation mode to reveal. Slides are intentionally designed to double up as revision notes for students, while being optimised for classroom usage. The Mini-Tasks on the DFM platform are purposely ordered to correspond to these slides, giving your flexibility over your lesson structure. ?

3 Why the need to access files?
Files are a means of storing data in a block (i.e. a potentially very long string), that is stored externally from the program that might be accessing it, e.g. stored on a hard disk. While most of the data used by programs on DrFrostMaths is stored in a database*, there are many times where I’ve had to access files… You can download a csv file on the Department for Education website, listing all schools in the UK. This includes the town, type of school and so on… I then wrote a script to add a record in the schools database for each line in this file. * Ultimately database data is stored in files, although you would never access the data directly from these files, but instead from appropriate database libraries to select and modify this data.

4 This is analogous to how we’d access a file…
Opening/Closing Files If you want to read a book, or write in it, we would first obviously need to open the book! Once we’ve done reading the book, or write in it, we’d close the book, protecting the pages until we next decide to open it. It also allows others to open the book to read it! If we had a ‘lock’ on the file (preventing other programs from accessing it), closing the file releases the lock. We can no longer read or write from the file (unless it is reopened). When you’ve got the book open, only you (generally) have access to it. This is analogous to how we’d access a file… We first open the file, either with the intention of reading from the file, or writing to it (whether replacing the data or appending onto the end). The operating system checks we have permissions for each type of access (reading or writing). e.g. A school library will allow you to open the book to read from it, but not write in it! This gives us a ‘handle’ to the file. We can use this handle to either read lines/characters from it or write lines/characters, depending on what permissions we opened the file with.

5 Opening/Closing Files
\n, known as the newline character, is a special character indicating the character after should start on a fresh line. Files consist of sequences of characters. H e l l o . \n L i n e 2 \n 3 EOF myfile.txt The stream maintains a cursor/pointer representing our current position in the file. We similarly have a special signal to indicate the end of file (EOF). (The following is pseudocode – we’ll look at a proper implementation in a language in a bit) We open the file, either for read access (openRead in pseudocode) or for write access (openWrite). We need to specify the file name (potentially with the path to it). This creates a handle to the file, which we’ve assigned to the variable file. Note that file isn’t the file itself (which is external), but a stream representing our access to the file. A stream is simply a sequence of data elements (here characters) made available one at a time… file = openRead("mystuff/myfile.txt") line1 = file.readLine() line2 = file.readLine() line3 = file.readLine() file.close() readLine() reads characters from the file stream until we hit a newline character. line1 will be assigned the value “Hello.” and the cursor will now be on the ‘L’ ready for more reading. We’ll similarly assign line2 the value “Line 2” and line3 the value “3”. If we were to try calling readLine again, we’d get an error, as we’ve reached the EOF. We close the file stream, relinquishing our access to it.

6 Further Examples ? New contents of file
This time we want to write to a file. We have the top 3 players in a game and want to output their names with their position. top3 = ["Ashwin", "Alice", "Alex"] file = openWrite("rankings.txt") for i = 0 to 2 file.writeLine(str(i+1) + ": " + top3[i]) next i file.close() ? New contents of file 1: Ashwin 2: Alice 3: Alex

7 Further Examples Albania array countries[] Armenia
countries.txt Albania Armenia Australia Austria ... array countries[] file = openRead("countries.txt") while NOT file.endOfFile() countries[i] = file.readLine() endwhile print(countries) endOfFile() is a function which returns true if the cursor is at the end of the file, and false otherwise. By using it in a while loop, it ensures we keep reading lines until we can’t read any more. Append the line that’s just been read to the array countries.

8 Characters vs Lines readLine() handily keeps on reading characters until we hit the next newline character. But we could also read individual characters using read(). We’d then have to handle newline characters ourselves… line maintains what we’ve read of the line so far. It starts off blank. file = openRead("myfile.txt") line = "" while NOT file.endOfFile() AND (c = file.read()) != ‘\n’ line = line + c endwhile print line Recall that when we assign a variable, it returns the value just assigned. It means we can then compare the character we just read (and assigned to c) against the newline character. If the character is a newline, the condition of the while is now longer met, so we stop reading characters. Each character we read is appended to the end of our line. Once done, output our fully read line.

9 Example implementation
This is some code I wrote in PHP to read school information from a file to add them to the database. The first part of the code simply put all the school information into an array, so I could later look at each line to extract the school’s name, location, age range, etc: $schools = array(); $sfile = fopen("schoolstoadd.txt", "r") or die("Unable to open file."); while(!feof($sfile)) { $line = trim(fgets($sfile)); if($line!="")$schools[] = $line; } fclose($sfile); foreach($schools as $s) { ... r here indicates we want read access to the file. trim removes any ‘whitespace characters’ (spaces, tabs) from each end of the string. e.g. trim(" Bob ")  "Bob"

10 Coding Mini-Tasks Return to the DrFrostMaths site to complete the various mini-coding tasks on this topic.


Download ppt "Programming Techniques :: File Handling"

Similar presentations


Ads by Google