Menu

File Handling

Why programs use files

While a program is running, the values stored in its variables and arrays sit in main memory. Main memory is volatile, so it keeps data only while the power is on. When the program finishes, or the machine loses power, those values vanish and the memory can be reused. Start the program again and every variable begins again from its starting value.

A file avoids this because it lives in secondary storage. Secondary storage is non-volatile, so the data is still there after the program has finished and after the machine has been switched off. Next time it runs, the program can open the file and read the saved values back. That is why a program that needs to remember something between runs saves it to a file instead of keeping it in a variable.

A worked example

Imagine a school gardening club program that asks for the height in centimetres of each sunflower and prints the tallest. If those measurements are held only in a variable inside a loop, they are gone once the program closes, so a club member must measure and type every height again at the next meeting. If the program instead writes each height into a text file as it is entered, the measurements are still on disk a week later, and a second program can open the same file to work out which sunflower has grown most over the term.

Reading data someone else made

A file can also be a source of information that a program did not produce itself. A canteen manager might type the day's meal prices into a text editor and save them as a file; the till program can open that file and use the prices, rather than having them typed into the code. The same works between programs: a weather station can log readings to a file, and a separate graphing program can open it to draw a chart. Because the data is kept apart from the program, it can be changed or added to without editing a single line of code.

Practise this