2012-04-06 74 views
2

我有以下代碼: -更改C文件創建日期++在Windows中使用WINDOWS.H 7

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

ofstream file("C:\\users\\Lenovo\\Documents\\varuntest.txt", ios::app);//creates a fie  
as varuntest.txt 
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; 

}

現在的問題是它只會改變當我檢查修改日期在文件的屬性中,我需要問如何更改文件的創建日期而不是修改日期。 感謝

請給這個新手

回答

5

一些代碼,它設置最後修改時間,因爲這是你要求它做的事。該函數接收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上查找它。

而且對你的代碼的一些意見:

  • 您應經常檢查返回值的API調用。如果您錯誤地調用了函數,或者出於某種其他原因而失敗了,那麼您將發現無法檢查錯誤就無法計算出錯。
  • 您調用的變量filename實際上應該被命名爲fileHandle
+0

thesystemtime.wDay = 07; //將更改日 thesystemtime.wMonth = 04; //改變月份 thesystemtime.wYear = 2012; //改變一年 u能提出好的建議通過當前系統日期 – gandhigcpp 2012-04-06 10:36:24

+0

@gandhigcpp在我回答另一個不同的問題之前,我是否可以請求您查看您現有的問題(包括這一問題),並在可能的情況下根據[faq]接受最有用的答案。 – 2012-04-06 10:39:42

+0

:我接受了它,但你也可以回覆我在評論 – gandhigcpp 2012-04-06 10:44:55

相關問題