12.10. Truncating a file

[<<<] [>>>]

When you write to a file it is automatically extended by the operating system and grows. On the other hand files do not shrink automatically. When you write into file before the position of the end of the file the bytes after the written region are still valid and remain in the file. The exception is when you open a file for output. In that case the original file is deleted and you can start to write of length zero,

However you may want to open a binary file, read from it, write into it and sometimes you may want to decrease the size of the file. The instruction truncate does it for you. The syntax of the instruction is:


Where fn is the opened file number, and size is the new size of the file in terms of records. The content of the file after the position size-1 is lost. Note that the argument to the instruction truncate is the desired length of the file, which is the position of the last byte or record plus one. Positions start with zero offset just like in file positioning statements.

If the specified length is larger than the actual length of the file then the file is elongated with bytes containing the value zero padded to the end of the file.

[<<<] [>>>]