PRB: Time and Date Are Written When File Is Flushed

ID: Q51123

5.10 6.00 6.00a 6.00ax 7.00 | 1.00 1.50

MS-DOS                      | WINDOWS
kbprg kbprb

The information in this article applies to:

SYMPTOMS

In Microsoft C, changing the time and date of a file with _dos_setftime() may appear to fail if the file is opened for write and all data has not been flushed from the C run-time buffers.

CAUSE

MS-DOS and OS/2 update file time and date stamps whenever a file gets modified. The C stream I/O functions use C run-time buffers to store data. The data from these buffers are sent to the operating system when the buffers become full, are flushed or when the file is closed. If an attempt is made to change the file date before all data has been flushed from the C buffers, the system will reset the date when it finally receives the data that remained in the C buffers.

RESOLUTION

One way to work around this feature of the operating system is to put a flush() statement before the call to _dos_setftime(). This ensures that all remaining data has been sent to the operating system before the date is changed and the file is closed. The following program changes the date to 6-1-89 10:00 successfully.

/* Compile options needed: none
*/ 

#include <stdio.h>
#include <dos.h>

void main(void)
{
    FILE *fp;
    fp = fopen( "outfile.txt", "wt" );
    fprintf( fp, "Start of file\n" );
    fprintf( fp, "End of file\n" );
    fflush(fp);     //       <---- flush the data to disk
    _dos_setftime( fileno( fp ), 0x12c1, 0x5000);  //  10:00  6-1-89
    fclose(fp);
}

MORE INFORMATION

The following program will attempt to modify the date and time of the output file to 6-1-89 10:00. Because the file has not been flushed or closed, it is likely that there is still data in the file buffer waiting to be sent to the operating system. When the file is closed, the program will flush all remaining data to the system, changing the date and time to the current date and time in the process.

/* Compile options needed: none
*/ 

#include <stdio.h>
#include <dos.h>

void main(void)
{
    FILE *fp;
    fp = fopen( "outfile.txt", "wt" );
    fprintf( fp, "Start of file\n" );
    fprintf( fp, "End of file\n" );
    _dos_setftime( fileno( fp ), 0x12c1, 0x5000);  //  10:00  6-1-89
    fclose(fp);
}

Additional reference words: 5.10 6.00 6.00a 6.00ax 7.00 1.00 1.50 KBCategory: kbprg kbprb KBSubcategory: CRTIss Keywords : kb16bitonly

Last Reviewed: July 18, 1997