On Fri 2008-06-06 18:09:18 UTC-0000, mikejd42 ([EMAIL PROTECTED]) wrote:

> I have a threaded program that one thread is reading file stats and
> another thread is comparing them. I have a need to modify the time
> stamp on a file before I close it. If I close the file then change the
> time stamp on the file I could wind up in a race condition that I can
> not deal with. 
> 
> 
> So the question is: Is is possible to create a new file, write into it, 
> modify the time stamp giving it a older update time then close the file?

My initial instinct was "no", but I wrote some code that proved that 
wrong, at least when I compile and run it on a FreeBSD 6.3 system.  I
can't vouch for other environments.

The important thing was to call fflush(), modify the last-modified
timestamp, then call fclose().  Otherwise, if there is unflushed data
in stdio's buffer, fclose() will call fflush() to write it, with the
OS consequently rewriting the timestamp with the current time.

#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>

#define MYFILE "myfile.dat"

int main(void)
{
    FILE *fp;
    struct timeval times[2];
    struct stat st;
    fp = fopen(MYFILE, "wb");
    fputs("Hello world.\n", fp);
    fflush(fp);
    memset(times, 0, sizeof times);
    utimes(MYFILE, times);
    fclose(fp);
    stat(MYFILE, &st);
    printf("st_mtime: %d\n", st.st_mtime);
    return 0;
}

Reply via email to