【问题标题】:Changing the File Creation Date in C++ using windows.h in Windows 7在 Windows 7 中使用 windows.h 在 C++ 中更改文件创建日期
【发布时间】:2012-04-06 09:34:19
【问题描述】:

我有以下代码:

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;
}

现在的问题是;当我检查文件的属性时,它只会更改修改日期。我需要问一下;

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

谢谢

请给这个新手一些代码。

【问题讨论】:

    标签: c++ file datetime file-properties


    【解决方案1】:

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

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

    我建议您阅读SetFileTime 的文档。关键部分是它的签名,如下:

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

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

    您的代码中还有一些 cmets:

    • 您应该始终检查任何 API 调用的返回值。如果您错误地调用了这些函数,或者它们由于某些其他原因而失败,您会发现如果不进行错误检查就无法找出问题所在。
    • 您调用filename 的变量实际上应该命名为fileHandle

    【讨论】:

    • thesystemtime.wDay = 07;//更改日期 thesystemtime.wMonth = 04;//更改月份 thesystemtime.wYear = 2012;//更改年份 你可以提出一些通过当前系统的建议日期
    • @gandhigcpp 在我回答另一个不同的问题之前,我能否请您检查一下您现有的问题(包括这个问题)并尽可能按照faq 接受最有帮助的答案。跨度>
    • :我接受了,但你也可以回复我在 cmets 中提出的问题
    • 还有其他问题呢?
    • :我一定会这样做的,实际上,一旦你回复了这个,我就必须完成一些事情,一旦我完成了一些事情,我肯定会这样做,这是一个你明天可以交叉检查的承诺
    猜你喜欢
    • 1970-01-01
    • 2018-08-18
    • 1970-01-01
    • 2011-06-27
    • 2010-10-27
    • 2012-04-10
    • 2014-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多