Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
Shopping.txt holds six lines: bread, rice, milk, eggs, tea and jam. Backup.txt already holds three lines from last week.
DECLARE Count : INTEGER
DECLARE Item : STRING
OPENFILE "Shopping.txt" FOR READ
OPENFILE "Backup.txt" FOR WRITE
FOR Count ← 1 TO 4
READFILE "Shopping.txt", Item
WRITEFILE "Backup.txt", Item
NEXT Count
CLOSEFILE "Shopping.txt"
CLOSEFILE "Backup.txt"How many lines does Backup.txt hold afterwards, and what is its last line? Change the program so that it copies the whole list.
OPENFILE <name> FOR READ or FOR WRITE (WRITE makes a new file and loses the old data), then READFILE <name>, <variable> to read the next line, or WRITEFILE <name>, <value> to write one, then CLOSEFILE <name>. Files keep data after the program stops.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Step 1. The old lines. Opening Backup.txt FOR WRITE creates a new file, so last week's lines are lost.
Step 2. The new lines. The loop runs 4 times, so bread, rice, milk and eggs are copied. The file holds 4 lines, and the last is eggs.
Step 3. The change. The list has 6 lines, so the loop must run 6 times. Better, use a constant:
CONSTANT Items ← 6
FOR Count ← 1 TO Items
READFILE "Shopping.txt", Item
WRITEFILE "Backup.txt", Item
NEXT CountAnswer: 4 lines, ending with eggs. Tea and jam are not copied.
Log in to join the discussion.
Loading…