21xrx.com
2024-09-20 00:08:50 Friday
登录
文章检索 我的文章 写文章
如何在C++中判断一个文件是否被修改过?
2023-06-22 18:26:58 深夜i     --     --
C++ 文件 修改 判断 时间戳

在C++中,判断一个文件是否被修改过可以通过比较文件的时间戳来实现。Windows和Unix操作系统都提供了获取和比较文件时间戳的API。

在Windows操作系统中,可以使用GetFileTime函数获取文件的创建时间、最后访问时间和最后修改时间。这些时间都以FILETIME结构体类型表示。可以通过将FILETIME转换为64位整数,来进行比较。

示例代码:


#include <iostream>

#include <windows.h>

bool hasFileBeenModified(LPCWSTR filePath) {

  FILETIME creationTime, lastAccessTime, lastWriteTime;

  SYSTEMTIME systemTime;

  ULARGE_INTEGER uintTime, modifiedTime;

 

  HANDLE handle = CreateFileW(filePath, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);

  if (handle == INVALID_HANDLE_VALUE)

    return false;

 

  if (!GetFileTime(handle, &creationTime, &lastAccessTime, &lastWriteTime)) {

    CloseHandle(handle);

    return false;

  }

  FileTimeToSystemTime(&lastWriteTime, &systemTime);

  SystemTimeToFileTime(&systemTime, &lastWriteTime);

  uintTime.LowPart = lastWriteTime.dwLowDateTime;

  uintTime.HighPart = lastWriteTime.dwHighDateTime;

  modifiedTime.QuadPart = uintTime.QuadPart;

 

  CloseHandle(handle);

  return modifiedTime.QuadPart > 0;

}

int main() {

  LPCWSTR filePath = L"C:/test.txt";

  bool hasBeenModified = hasFileBeenModified(filePath);

  std::cout << "File has been modified: " << hasBeenModified << std::endl;

  return 0;

}

在Unix操作系统中,可以使用stat函数获取文件的创建时间、最后访问时间和最后修改时间。这些时间都以time_t类型表示。可以通过将time_t转换为time_t类型,来进行比较。

示例代码:


#include <iostream>

#include <sys/stat.h>

bool hasFileBeenModified(const char *filePath) {

  struct stat fileStat;

  if (stat(filePath, &fileStat) < 0)

    return false;

 

  time_t modifiedTime = fileStat.st_mtime;

 

  return modifiedTime > 0;

}

int main() {

  const char *filePath = "/home/test.txt";

  bool hasBeenModified = hasFileBeenModified(filePath);

  std::cout << "File has been modified: " << hasBeenModified << std::endl;

  return 0;

}

需要注意的是,只判断文件是否被修改过,并不能完全保证文件的内容是否被篡改。如果文件内容很重要,建议使用文件内容的校验和或数字签名等技术进行验证。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复