File and Device I/O The following programming examples illustrate how to code file I/O and device I/O statements. Example 1 - Sequential File I/O The following short program creates a sequential file named "Price.Dat," then adds data entered at the keyboard to the file. The OPEN statement in this program both creates the file and readies the file to receive records. The WRITE # then writes each record to the file. Note that the number used in the WRITE # statement is the same number given to the file name Price.Dat in the OPEN statement. ' Create a file named Price.Dat ' and open it to receive new data: OPEN "Price.Dat" FOR OUTPUT AS #1 DO ' Continue putting new records in Price.Dat until the ' user presses ENTER without entering a company name: ' INPUT "Company (press <> to quit): ", Company$ IF Company$ <> "" THEN ' Enter the other fields of the record: INPUT "Style: ", Style$ INPUT "Size: ", Size$ INPUT "Color: ", Clr$ INPUT "Quantity: ", Qty ' Put the new record in the file ' with the WRITE # statement: WRITE #1, Company$, Style$, Size$, Clr$, Qty END IF LOOP UNTIL Company$ = "" ' Close Price.Dat (this ends output to the file): CLOSE #1 END Example 2 - Sequential File I/O The following program opens the Price.Dat file created in "Example 1 - Sequential File I/O" and reads the records from the file, displaying the complete record on the screen if the quantity for the item is less than the input amount. The INPUT #1 statement reads one record at a time from Price.Dat, assigning the fields in the record to the variables Company$, Style$, Size$, Clr$, and Qty. Since this is a sequential file, the records are read in order from the first one entered to the last one entered. The EOF (End Of File) function tests whether the last record has been read by INPUT #. If the last record has been read, EOF returns the value 1 (true), and the loop for getting data ends; if the last record has not been read, EOF returns the value 0 (false), and the next record is read from the file. OPEN "Price.Dat" FOR INPUT AS #1 INPUT "Display all items below what level"; Reorder DO UNTIL EOF(1) INPUT #1, Company$, Style$, Size$, Clr$, Qty IF Qty < Reorder THEN PRINT Company$, Style$, Size$, Clr$, Qty END IF LOOP CLOSE #1 END Example 3 - Sequential File I/O The WRITE # statement can be used to write records to a sequential file. There is, however, another statement you can use to write sequential file records: PRINT # The best way to show the difference between these two data-storage statements is to examine the contents of a file created with both. The following short fragment opens a file Test.Dat then places the same record in it twice, once with WRITE # and once with PRINT #. After running this program you can examine the contents of Test.Dat with the DOS TYPE command: OPEN "Test.Dat" FOR OUTPUT AS #1 Nm$ = "Penn, Will" Dept$ = "User Education" Level = 4 Age = 25 WRITE #1, Nm$, Dept$, Level, Age PRINT #1, Nm$, Dept$, Level, Age CLOSE #1