Lesson goal: Reading all data from a file

Previous: Reading all data from a file (1) | Home | Next: Testing for the end of file (EOF)

In the last lesson, you learned how to read all lines of data from a file using a while-loop.

While loops are always funny, in that depending on conditions of your code, the loop may not be executed at all. For example, consider this:

x=5
while x < 5 do
...
...
end

Here the while-loop will never be entered, since x<5 is false, because x=5 just before the while-loop is encountered.

In our data reading loop, we had to set data = true before the while-loop, to get it started. Yes, while-loops need to be "primed" or they may not run. In the last lesson, setting data=true "primed" the while loop properly.

Wouldn't it be nice if there was a looping structure that always ran at least once, with no priming required? There is! It's called the repeat-until loop. Let's try it.

repeat
CODE
until CONDITION-IS-TRUE
Move the mouse over a dotted box for more information.

Here, let's try using a repeat-until-loop, and keep reading line after line, until file_read returns a false?

Now you try. Fill in the ??? in the until ??? line with a suitable condition that will print all data in the sample.dat file.

Type your code here:


See your results here:

This code will not run! Fill in the until = ??? with a suitable condition that will display all data in the sample.dat file.

If everything works, you should see a long list of numbers appear. These will be all of the numbers in the file screen.dat. Dismiss.

Show a friend, family member, or teacher what you've done!

Here is a share link to your code:

Does your code work? Want to run it on your iPhone?

Here's your code:

  1. Use [Control]-[C] (Windows) or [⌘]-[C] (MacOS) to copy your code.

  2. Paste it using [Control]-[V] (Windows) or [⌘]-[V] (MacOS) into this page

  3. Then click the "Use on iPhone" button that you'll see.