Changing the File Creation Date in C++ using windows.h in Windows 7

断了今生、忘了曾经 提交于 2019-12-10 09:33:06

问题


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 to change the file's creation date instead of the modification date?

Thanks

Please give some code for this novice.


回答1:


It sets the last modified time because that's what you asked it to do. The function receives 3 filetime parameters and you only passed a value to the final one, lpLastWriteTime. To set the creation time call the function like this:

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

I suggest you take a read of the documentation for SetFileTime. The key part is its signature which is as follows:

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 a novice with the Windows API I'll give you a tip. The documentation on MSDN is very comprehensive. Whenever you get stuck with a Win32 API call, look it up on MSDN.

And some comments on your code:

  • You should always check the return values for any API calls. If you call the functions incorrectly, or they fail for some other reason, you'll find it impossible to work out what went wrong without error checking.
  • The variable that you call filename should in fact be named fileHandle.


来源:https://stackoverflow.com/questions/10041651/changing-the-file-creation-date-in-c-using-windows-h-in-windows-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!