From: MERC::"uunet!CRVAX.SRI.COM!RELAY-INFO-VAX" 2-FEB-1993 21:53:17.60 To: Info-VAX@SRI.com CC: Subj: read/write to files in PASCAL One person wondered why his Pascal program doesn't update records in a file, and another posted an incorrect answer. Pascal I/O works well, but not the way most people think it should. First, you OPEN a file, which opens it but puts it into an undefined state, then you RESET an old file, which positions it to the first record, or REWRITE a new file, which makes it ready to write the first record. GET, UPDATE, and PUT are the data transfer primitives, and can be confusing. Blame Prof. Wirth, not me or DEC if you don't like the way they work. RESET positions a file to its first record. Once positioned to a record, you get and update the data by treating the file variable as a record pointer: buffer := file_variable^; (* get the current record *) file_variable^.field := new_value; (* update one field *) file_variable^ := buffer; (* update the whole record *) When finished with the record, you UPDATE the file variable, then GET the file variable, which positions it to the next record or the end of the file: open (file_variable, 'file.type', old); reset (file_variable); while not eof (file_variable) do begin buffer := file_variable^; (* get the current record *) (* process the buffer *) if update_it then begin file_variable^ := buffer; (* prepare for update *) update (file_variable) (* update current record in file *) end; get (file_variable) (* position to next record or EOF *) end; Note the assignment from the file variable treated as a pointer to a buffer, and the separate GET to position to the next record or EOF; and the assignment to the file variable treated as a pointer and the separate UPDATE to actually update the disk file. READ is a handy shortcut if you are not updating. It does an assignment and then a GET, which immediately positions to the next record, which leaves you unable to update what you just read: open (file_variable, 'file.type', readonly); reset (file_variable); repeat (* assuming there is at least one record in the file *) read (file_variable, buffer); (* do something read only with it *) until eof (file_variable); Likewise, to write a record, first you assign a record to a file variable treated as a pointer, then you PUT the file variable: file_variable^ := buffer; put (file_variable); WRITE is a handy shortcut that works in most cases. It does an assignment and then a PUT, which, unlike READ, usually leaves the file positioned to where you think it should be. If you are still confused, feel free to call me. Tony Scandora, Argonne National Lab, 708-252-7541 scandora@cmt.anl.gov or scandora@anlcmt.bitnet