我在 Windows 中將檔案從一個檔案夾移動到另一個檔案夾,并希望將原始檔案日期戳保存到新檔案中。我可以使用 <utime.h> 和 <sys/stat.h> 成功復制訪問日期和修改日期我還想在適用的情況下復制創建日期。我看到 C 有 GetFileTime 函式 (fileapi.h) 可以做到這一點,而其他語言可以做到這一點。可以純粹用 C 語言完成嗎?如果可以,怎么做?
uj5u.com熱心網友回復:
Windows API 設計為從 C 呼叫。寫
#include <windows.h>
在 C 程式中,編譯器將接受 and 的GetFileTime使用SetFileTime。然后,您需要鏈接kernel32.lib匯入庫,默認情況下它可能已經在您的庫串列中。
C 實際上必須使用extern "C"來呼叫這些函式,因為它們根本不是 C 函式(頭檔案會自動執行此操作,#if __cplusplus因此您不必擔心它。頭檔案還會自動使用stdcall呼叫標記這些宣告x86 上的約定,除非您形成函式指標,否則您也不必擔心這一點。)
uj5u.com熱心網友回復:
這適用于我的 Window 10 系統。謝謝您的幫助。
#include <windows.h>
#include <stdio.h>
int main()
{
HANDLE hFile1, hFile2;
FILETIME ftCreate1, ftAccess1, ftWrite1, ftCreate2, ftAccess2, ftWrite2;
SYSTEMTIME st, stUTC, stLocal;
// file names, change accordingly
char fname1[ ] = "C:\\PathToFile\\testfile01.txt";
char fname2[ ] = "C:\\PathToFile\\testfile02.txt";
BOOL bRet = FALSE;
//OPEN FILES
// open first file
hFile1 = CreateFile(
fname1, // file to open
GENERIC_READ, // open for reading
FILE_SHARE_READ, // share for reading
NULL, // default security
OPEN_EXISTING, // existing file only
FILE_ATTRIBUTE_NORMAL, // normal file
NULL // no attribute template
);
// open second file
hFile2 = CreateFile(
fname2, // file to open
GENERIC_WRITE, // open for writing
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL
);
// check file handles have opened successfully
if(hFile1 == INVALID_HANDLE_VALUE){
printf("Could not open %s file, error %d\n", fname1, GetLastError());
return 1;
}
if(hFile2 == INVALID_HANDLE_VALUE){
printf("Could not open %s file, error %d\n", fname2, GetLastError());
return 1;
}
// GET FILE TIMES
// retrieve the file times from the first file.
if(!GetFileTime(hFile1, &ftCreate1, &ftAccess1, &ftWrite1)){
printf("GetFileTime Failed!\n");
return 1;
}
// SYSTEM TIME
// get system time and assign to variable for saving current time - if required
GetSystemTime(&st); // gets current time
SystemTimeToFileTime(&st, &ftAccess2); // converts to file time
// SET TIME ON FILE!!!
// set file times for second file, NULL to keep existing timestamp
if(SetFileTime(hFile2, &ftCreate1, &ftAccess2, NULL)){
printf("SetFileTime Successful!\n");
}else{
printf("SetFileTime Failed!\n");
return 1;
}
// PRINT
// convert filetime to readable date format for printing to stdout
FileTimeToSystemTime(&ftCreate1, &stUTC);
SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
printf("Created: d/d/%d d:d\n", stLocal.wDay, stLocal.wMonth, stLocal.wYear, stLocal.wHour, stLocal.wMinute);
// close the file handles
CloseHandle(hFile1);
CloseHandle(hFile2);
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/418328.html
標籤:
