In the last lesson, you learned how to read a line from a data file. But wait! Often data files can contain 100s, 1000s, or even millions of lines of data! How do we get to them all?
You'll still use file_read, but now you have to use a bit of your programming logic (and a while loop):
Move the mouse over a dotted box for more information.
Now, here's the logic. The return from file_read is stated to be false if 'something went wrong.' What could go wrong? Plenty, but here, all that can really happen is that you try to read more data than the file has to offer. We can use this false return value to read all data from sample.dat. How?
How about use a while-loop, and keep it reading line after line, until file_read returns a false?
Now you try. Fill in the data = ??? and the while data ~= ??? do lines. See if you can print all data in the sample.dat file.
Type your code here:
See your results here:
This code will not run! Fill in the data = ??? line with a good starting value to "prime" you loop and the while data ~= ??? do line with suitable condition to run the while loop.
Hint: each ??? will either be a true or false. But think carefully. Your choice for the data = ??? line, must allow the while loop to start, and your choice for the while data ~= ??? do must stop the while-loop when file_read returns false.
If everything works, you should see a long list of numbers appear. These will be all of the numbers in the file screen.dat.
Share your code
Show a friend, family member, or teacher what you've done!