8.6 Truncating a File


8.6 Truncating a File

If you open an existing file (using fileio.open) for output and write data to that file, it overwrites the existing data from the start of the file. However, if the new data you write to the file is shorter than the data originally appearing in the file, the excess data from the original file, beyond the end of the new data you've written, will still appear at the end of the new data. Sometimes this might be desirable, but most of the time, you'll want to delete the old data after writing the new data.

One way to delete the old data is to use the fileio.opennew function to open the file. The fileio.opennew function automatically deletes any existing file so only the data you write to the file will be present in the file. However, there may be times when you may want to read the old data first, rewind the file, and then overwrite the data. In this situation, you'll need a function that will truncate the old data at the end of the file after you've written the new data. The fileio.truncate function accomplishes this task. This function uses the following calling syntax:

 fileio.truncate( fileHandle ); 

Note that this function does not close the file. You still have to call fileio.close to commit the data to the disk.

The program in Listing 8-7 demonstrates the use of the fileio.truncate function.

Listing 8-7: Using fileio.truncate to Eliminate Old Data from a File.

start example
 program TruncateDemo; #include( "stdlib.hhf" ) static    fileHandle:dword;    u:uns32; begin TruncateDemo;    fileio.openNew( "myfile.txt" );    mov( eax, fileHandle );    for( mov( 0, ecx ); ecx < 20; inc( ecx )) do       fileio.put( fileHandle, (type uns32 ecx), nl );    endfor;    // Okay, let's rewind to the beginning of the file and    // rewrite the first ten lines and then truncate the    // file at that point.    fileio.rewind( fileHandle );    for( mov( 0, ecx ); ecx < 10; inc( ecx )) do       fileio.put( fileHandle, (type uns32 ecx), nl );    endfor;    fileio.truncate( fileHandle );    // Rewind and display the file contents to ensure that    // the file truncation has worked.    fileio.rewind( fileHandle );    while( !fileio.eof( fileHandle )) do       // Read and display the next item from the file:       fileio.get( fileHandle, u );       stdout.put( "u=", u, nl );       fileio.readLn( fileHandle );    endwhile;    fileio.close( fileHandle ); end TruncateDemo; 
end example




The Art of Assembly Language
The Art of Assembly Language
ISBN: 1593272073
EAN: 2147483647
Year: 2005
Pages: 246
Authors: Randall Hyde

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net