在Windows 7中使用Windows.h在C++中更改文件创建日期

gan*_*cpp 4 c++ datetime file file-properties

我有以下代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

现在的问题是; 它只在我检查文件属性时更改修改日期.我需要问;

如何更改文件的创建日期而不是修改日期?

谢谢

请给这个新手一些代码.

Dav*_*nan 5

它设置了上次修改时间,因为这就是您要求它执行的操作.该函数接收3个文件时参数,您只将值传递给最后一个,lpLastWriteTime.要设置创建时间,请调用以下函数:

SetFileTime(filename, &thefiletime, (LPFILETIME) NULL,(LPFILETIME) NULL);
Run Code Online (Sandbox Code Playgroud)

我建议你阅读一下文档SetFileTime.关键部分是其签名如下:

BOOL WINAPI SetFileTime(
  __in      HANDLE hFile,
  __in_opt  const FILETIME *lpCreationTime,
  __in_opt  const FILETIME *lpLastAccessTime,
  __in_opt  const FILETIME *lpLastWriteTime
);
Run Code Online (Sandbox Code Playgroud)

既然你说你是Windows API的新手,我会给你一个提示.MSDN上的文档非常全面.每当您遇到Win32 API调用时,请在MSDN上查找.

以及对您的代码的一些评论:

  • 您应该始终检查任何API调用的返回值.如果你错误地调用这些函数,或者由于某些其他原因它们失败了,你会发现在没有错误检查的情况下找不到出错的地方是不可能的.
  • 您调用的变量filename实际上应该被命名fileHandle.