Question 1 Report
A file inventory.txt stores product stock levels in the format "ProductName,Quantity". A program needs to update the quantity for a specific product.
(a) Write pseudocode to update the quantity of a given product. Since text files cannot be modified in-place, you must read the original file, write to a temporary file with the updated record, then replace the original. [6]
(b) Explain why a temporary file is needed for this operation. [2]
(c) State what would happen if the program crashes after writing the temporary file but before replacing the original. [2]
(a) The update algorithm reads every record from the original file, writes each one to a temporary file, and substitutes the updated quantity for the matching product. After processing, the temporary file contains the complete updated data. [6]
DECLARE SearchProduct : STRING
DECLARE NewQuantity : INTEGER
DECLARE Line : STRING
DECLARE ProductName : STRING
DECLARE CommaPos : INTEGER
DECLARE i : INTEGER
DECLARE Found : BOOLEAN
DECLARE UpdatedLine : STRING
OUTPUT "Enter product to update: "
INPUT SearchProduct
OUTPUT "Enter new quantity: "
INPUT NewQuantity
Found ← FALSE
OPENFILE "inventory.txt" FOR READ
OPENFILE "temp.txt" FOR WRITE
WHILE NOT EOF("inventory.txt") DO
READFILE "inventory.txt", Line
CommaPos ← 0
FOR i ← 1 TO LENGTH(Line)
IF Line[i] = ',' THEN
CommaPos ← i
ENDIF
NEXT i
ProductName ← SUBSTRING(Line, 1, CommaPos - 1)
IF ProductName = SearchProduct THEN
UpdatedLine ← ProductName & "," & NUM_TO_STR(NewQuantity)
WRITEFILE "temp.txt", UpdatedLine
Found ← TRUE
ELSE
WRITEFILE "temp.txt", Line
ENDIF
ENDWHILE
CLOSEFILE "inventory.txt"
CLOSEFILE "temp.txt"
IF Found THEN
OUTPUT "Product updated successfully"
ELSE
OUTPUT "Product not found"
ENDIFThe algorithm works through these stages:
(b) A temporary file is needed because text files are sequential-access and do not support modifying individual records in place. [2]
When a text file is opened for reading, data can only be read sequentially from start to end. There is no mechanism to seek to a specific record and overwrite just that record's quantity. If the new quantity has a different number of digits than the old one, the record would be a different length, which would corrupt all subsequent records by shifting their positions. The only reliable approach is to read each record, decide whether to modify it, and write the result to a new file.
(c) If the program crashes after writing the temporary file but before replacing the original: [2]
Everything you need to excel in your exams