开启辅助访问 切换到宽版

精易论坛

 找回密码
 注册

QQ登录

只需一步,快速开始

用微信号发送消息登录论坛

新人指南 邀请好友注册 - 我关注人的新帖 教你赚取精币 - 每日签到


求职/招聘- 论坛接单- 开发者大厅

论坛版规 总版规 - 建议/投诉 - 应聘版主 - 精华帖总集 积分说明 - 禁言标准 - 有奖举报

查看: 658|回复: 3
收起左侧

[C/C++] 文件比较

[复制链接]
结帖率:25% (1/4)
发表于 2023-3-23 00:10:19 | 显示全部楼层 |阅读模式   辽宁省营口市
20精币
从U盘复制文件到指定目录,检查目录内文件,有变化复制,没有变化不复制。复制指定文件大小及格式的文件


回答提醒:如果本帖被关闭无法回复,您有更好的答案帮助楼主解决,请发表至 源码区 可获得加分喔。
友情提醒:本版被采纳的主题可在 申请荣誉值 页面申请荣誉值,获得 1点 荣誉值,荣誉值可兑换荣誉会员、终身vip用户组。
快捷通道:申请荣誉值无答案申请取消悬赏投诉有答案未采纳为最佳
结帖率:100% (3/3)
发表于 2023-3-23 00:37:39 | 显示全部楼层   黑龙江省哈尔滨市
[C++] 纯文本查看 复制代码
#include <iostream>
#include <fstream>
#include <cstring>
#include <windows.h>

using namespace std;

// 定义函数 check_file,用于检查文件是否存在且已修改
bool check_file(const char *path, const char *last_modified_time) {
    WIN32_FIND_DATAA data;
    HANDLE hFind;
    char search_path[MAX_PATH] = "";
    strcpy(search_path, path);
    strcat(search_path, "\\*.*");
    hFind = FindFirstFileA(search_path, &data);
    if (hFind != INVALID_HANDLE_VALUE) {
        do {
            // 排除"."和".."两个特殊目录
            if (strcmp(data.cFileName, ".") == 0 || strcmp(data.cFileName, "..") == 0)
                continue;
                
            // 获取文件修改时间
            FILETIME ftWrite;
            SYSTEMTIME stUTC, stLocal;
            ftWrite = data.ftLastWriteTime;
            FileTimeToSystemTime(&ftWrite, &stUTC);
            SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
            char file_modified_time[20];
            sprintf(file_modified_time, "%04d-%02d-%02d %02d:%02d:%02d", 
                    stLocal.wYear, stLocal.wMonth, stLocal.wDay,
                    stLocal.wHour, stLocal.wMinute, stLocal.wSecond);

            // 比较文件修改时间和上次检查时间
            if (strcmp(file_modified_time, last_modified_time) > 0)
                return true;
        } while (FindNextFileA(hFind, &data));
        FindClose(hFind);
    }
    return false;
}

// 定义函数 copy_file,用于复制指定格式和大小的文件
void copy_file(const char *src_file, const char *dest_dir, const char *file_ext, int max_size) {
    ifstream ifs(src_file, ios::binary | ios::ate);
    int file_size = ifs.tellg();  // 获取文件大小
    ifs.seekg(0, ios::beg);
    if (file_size > max_size) {
        cout << "File size exceeds the maximum specified value." << endl;
        return;
    }
    if (strstr(src_file, file_ext) == NULL) {
        cout << "File format does not match the specified value." << endl;
        return;
    }
    char dest_path[MAX_PATH] = "";
    strcpy(dest_path, dest_dir);
    strcat(dest_path, "\\");
    strcat(dest_path, strrchr(src_file, '\\') + 1);
    ofstream ofs(dest_path, ios::binary);
    ofs << ifs.rdbuf();
    cout << "File copied successfully!" << endl;
}

int main() {
    char u_disk[] = "E:";
    char dest_dir[] = "D:\\test\\";
    char file_ext[] = ".txt";
    int max_size = 1024;
    char last_modified_time[20] = "1970-01-01 00:00:00";  // 初始值为 1970-01-01 00:00:00,表示目录中所有文件都未被修改过

    while (true) {
        if (GetDriveTypeA(u_disk) == DRIVE_REMOVABLE) {  // 如果 U 盘已插入
            if (check_file(dest_dir, last_modified_time)) {  // 如果目录中的文件被修改过
                copy_file(u_disk, dest_dir, file_ext, max_size);  // 复制指定格式和大小的文件
                SYSTEMTIME st;
                GetLocalTime(&st);
                sprintf(last_modified_time, "%04d-%02d-%02d %02d:%02d:%02d",
                        st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);  // 更新目录的最后修改时间
            }
        }
        Sleep(5000);  // 每隔 5 秒钟检查一次
    }

    return 0;
}
回复

使用道具 举报

结帖率:100% (7/7)

签到天数: 13 天

发表于 2023-3-23 00:54:37 | 显示全部楼层   海南省海口市
取文件的MD5值  一样就移动文件  
回复

使用道具 举报

结帖率:100% (18/18)

签到天数: 2 天

发表于 2023-3-24 22:55:03 | 显示全部楼层   陕西省安康市
[C++] 纯文本查看 复制代码
#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <dirent.h>
#include <sys/stat.h>

using namespace std;

/**
 * @brief 复制指定文件。
 *
 * @param srcFile 源文件路径。
 * @param dstFile 目标文件路径。
 */
void copyFile(const string& srcFile, const string& dstFile)
{
    FILE* fin = fopen(srcFile.c_str(), "rb"); // 以二进制只读模式打开源文件
    if (fin == NULL) {
        perror("Open source file error"); // 打开源文件错误
        return;
    }

    FILE* fout = fopen(dstFile.c_str(), "wb"); // 以二进制写入模式创建目标文件
    if (fout == NULL) {
        perror("Create target file error"); // 创建目标文件错误
        fclose(fin);
        return;
    }

    char buffer[1024];
    size_t n;

    while ((n = fread(buffer, 1, sizeof(buffer), fin)) > 0) { // 读取源文件内容,写入目标文件中,直到读取完毕
        fwrite(buffer, 1, n, fout);
    }

    fclose(fin);
    fclose(fout); // 关闭文件
}

/**
 * @brief 判断指定源文件是否被修改过。
 *
 * @param srcFile 源文件路径。
 * @param dstFile 目标文件路径。
 * @Return bool 返回源文件是否被修改过。
 */
bool isFileModified(const string& srcFile, const string& dstFile)
{
    struct stat statSrc;
    struct stat statDst;

    if (stat(srcFile.c_str(), &statSrc) < 0) { // 获取源文件属性
        perror("Get source file stat error"); // 获取属性失败
        return true;
    }

    if (stat(dstFile.c_str(), &statDst) < 0) { // 获取目标文件属性
        return true; // 目标文件不存在,需复制
    }

    if (statSrc.st_size != statDst.st_size) { // 文件大小不同,需复制
        return true;
    }

    if (statSrc.st_mtime != statDst.st_mtime) { // 文件修改时间不同,需复制
        return true;
    }

    return false;
}

/**
 * @brief 递归地遍历指定目录下的所有文件和目录,筛选出符合条件的文件并复制到指定目录中。
 *
 * @param srcDir 源目录路径。
 * @param dstDir 目标目录路径。
 */
void copyFiles(const string& srcDir, const string& dstDir)
{
    DIR* dir = opendir(srcDir.c_str()); // 打开源目录
    if (dir == NULL) {
        perror("Open directory error"); // 打开目录错误
        return;
    }

    dirent* dp; // Dirent 结构体用于存储文件名信息

    while ((dp = readdir(dir)) != NULL) { // 循环读取目录下的文件和子目录
        string fileName = dp->d_name;
        if (fileName == "." || fileName == "..") {
            continue; // 跳过 "." 和 ".." 目录
        }

        string srcFile = srcDir + "/" + fileName;
        string dstFile = dstDir + "/" + fileName;

        if (dp->d_type == DT_DIR) { // 如果是子目录,则递归遍历子目录
            copyFiles(srcFile, dstFile);
        } else if (dp->d_type == DT_REG) { // 如果是普通文件
            struct stat st;
            if (stat(srcFile.c_str(), &st) < 0) {
                perror("Get source file stat error"); // 获取文件属性失败
                continue;
            }
            if (st.st_size <= 100 * 1024 && (endsWith(fileName, ".txt") || endsWith(fileName, ".pdf") || endsWith(fileName, ".doc"))) {
                if (isFileModified(srcFile, dstFile)) { // 判断是否需要复制文件
                    cout << "Copying file " << srcFile << " to " << dstFile << endl;
                    copyFile(srcFile, dstFile); // 复制文件
                }
            }
        } else {
            // Ignore other types of files
        }
    }

    closedir(dir); // 关闭目录
}

int main()
{
    string srcDir = "/media/usb"; // U盘路径
    string dstDir = "/home/user/target"; // 目标路径

    copyFiles(srcDir, dstDir); // 复制文件

    cout << "Copy finished." << endl;

    return 0;
}
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则 致发广告者

发布主题 收藏帖子 返回列表

sitemap| 易语言源码| 易语言教程| 易语言论坛| 诚聘英才| 易语言模块| 手机版| 广告投放| 精易论坛
拒绝任何人以任何形式在本论坛发表与中华人民共和国法律相抵触的言论,本站内容均为会员发表,并不代表精易立场!
论坛帖子内容仅用于技术交流学习和研究的目的,严禁用于非法目的,否则造成一切后果自负!如帖子内容侵害到你的权益,请联系我们!
防范网络诈骗,远离网络犯罪 违法和不良信息举报电话0663-3422125,QQ: 800073686,邮箱:800073686@b.qq.com
Powered by Discuz! X3.4 揭阳市揭东区精易科技有限公司 ( 粤ICP备12094385号-1) 粤公网安备 44522102000125 增值电信业务经营许可证 粤B2-20192173

快速回复 返回顶部 返回列表