溫馨提示×

如何用C++檢測文件是否已被覆蓋

c++
小樊
95
2024-09-06 08:32:25
欄目: 編程語言

要使用C++檢測文件是否已被覆蓋,你可以使用文件的最后修改時間

#include<iostream>
#include <fstream>
#include <sys/stat.h>
#include <unistd.h>

bool isFileModified(const std::string& filePath, time_t lastModificationTime) {
    struct stat fileInfo;
    if (stat(filePath.c_str(), &fileInfo) == 0) {
        return fileInfo.st_mtime > lastModificationTime;
    } else {
        // 無法獲取文件信息,可能文件不存在或其他錯誤
        return false;
    }
}

int main() {
    std::string filePath = "path/to/your/file.txt";
    struct stat fileInfo;

    // 獲取文件的最后修改時間
    if (stat(filePath.c_str(), &fileInfo) != 0) {
        std::cerr << "Error: Unable to get file information."<< std::endl;
        return 1;
    }

    time_t lastModificationTime = fileInfo.st_mtime;

    // 在此處執行你想要檢查文件是否被覆蓋的操作

    // 檢查文件是否已被覆蓋
    bool isModified = isFileModified(filePath, lastModificationTime);
    if (isModified) {
        std::cout << "The file has been overwritten."<< std::endl;
    } else {
        std::cout << "The file has not been overwritten."<< std::endl;
    }

    return 0;
}

這個示例首先獲取文件的最后修改時間,然后執行一些操作(在此示例中,這部分代碼未實現)。之后,它再次檢查文件的最后修改時間并與之前的時間進行比較。如果時間發生了變化,說明文件已被覆蓋。請注意,這個方法并不完美,因為文件可能在檢查之間被修改,但在實際應用中,這種方法通常足夠了。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女