Changing file creation date in C ++ using windows.h on Windows 7

I have the following code:

int main(int argc, char** argv) {
    onelog a;
    std::cout << "a new project";

    //creates a file as varuntest.txt
    ofstream file("C:\\users\\Lenovo\\Documents\\varuntest.txt", ios::app);

    SYSTEMTIME thesystemtime;
    GetSystemTime(&thesystemtime);

    thesystemtime.wDay = 07;//changes the day
    thesystemtime.wMonth = 04;//changes the month
    thesystemtime.wYear = 2012;//changes the year

    //creation of a filetimestruct and convert our new systemtime
    FILETIME thefiletime;

    SystemTimeToFileTime(&thesystemtime,&thefiletime);

    //getthe handle to the file
    HANDLE filename = CreateFile("C:\\users\\Lenovo\\Documents\\varuntest.txt", 
                                FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ|FILE_SHARE_WRITE,
                                NULL, OPEN_EXISTING, 
                                FILE_ATTRIBUTE_NORMAL, NULL);

    //set the filetime on the file
    SetFileTime(filename,(LPFILETIME) NULL,(LPFILETIME) NULL,&thefiletime);

    //close our handle.
    CloseHandle(filename);


    return 0;
}

      

Now the question is, it only changes the modified date when I check the properties of the file. I need to ask:

How can I change the file creation date instead of changing the date?

thank

Please give some code for this newbie.

+3


source to share


1 answer


It sets the last modified time because this is what you asked for. Function receives 3 parameters time file, and you just passed the final value lpLastWriteTime

. To set the creation time, call the function as follows:

SetFileTime(filename, &thefiletime, (LPFILETIME) NULL,(LPFILETIME) NULL);

      

I suggest you read the documentation for SetFileTime

. The key part is her signature, which looks like this:

BOOL WINAPI SetFileTime(
  __in      HANDLE hFile,
  __in_opt  const FILETIME *lpCreationTime,
  __in_opt  const FILETIME *lpLastAccessTime,
  __in_opt  const FILETIME *lpLastWriteTime
);

      



Since you say that you are new to the Windows API, I'll give you some advice. The MSDN documentation is very extensive. Whenever you get stuck with a Win32 API call, look for it on MSDN.

And some comments on your code:

  • You should always check the return values ​​for any API calls. If you call functions incorrectly, or they don't work for some other reason, you won't be able to decide what went wrong without checking for errors.
  • The variable you are calling filename

    must be named fileHandle

    .
+5


source







All Articles