windows控制台程序实现文件夹内容拷贝

27 篇文章 0 订阅

主要思路就是利用windows提供的api进行处理, 主要涉及 createDirectory, CFindFile类的操作, CopyFile,
遇到的主要问题是, windows 控制台好像不太支持unicode, 连输入的英文都是乱码的, 于是没办法, 写了一个转化函数, 将string 类型转为wstring类型, 从而实现整体功能。

代码如下:

#define _AFXDLL

#include <afxwin.h>
#include <windows.h>
#include <string>
#include <fstream>
#include <iostream>
#include <algorithm>

using namespace std;

/************************************************************************/
/* 将string 类型转化为 wstring 类型                                     */
/************************************************************************/
wstring string2wstring(string str){
    wstring wstr(str.length(), L' ');
    copy(str.begin(), str.end(), wstr.begin());
    return wstr;
}

/************************************************************************/
/* 这里windows 控制台好像不支持unicode 连英文都是乱码, 只能使用 
                string2wstring 转化                                     */
/************************************************************************/
int main(int argc, char* argv[]){
    if (argc != 3)
        return -1;

    string filepath_s(argv[1]);
    wstring filepath = string2wstring(filepath_s);
    filepath += L"\\*.*";
    wstring newpath(string2wstring(argv[2]));
    newpath += L"\\";

    // 创建目标文件夹目录
    CreateDirectory(newpath.c_str(), nullptr);

    CFileFind finder;
    // 查找文件
    bool bWorking = finder.FindFile(filepath.c_str());
    while (bWorking){
        bWorking = finder.FindNextFile();

        // 获取文件名
        wstring name = finder.GetFileName();

        // 排除 . / .. / 子文件夹
        if (finder.IsDots() || finder.IsDirectory())
            continue;

        // 设置拷贝文件路径
        wstring newname = newpath + name;
        wstring filename = finder.GetFilePath();

        // 计算拷贝时间
        DWORD t1 = GetTickCount();
        bool ret = CopyFile(filename.c_str(), newname.c_str(), true);
        if (!ret){
            cerr << "error code : " << GetLastError() << endl;
            system("pause");
            return -1;
        }
        DWORD t2 = GetTickCount();
        DWORD gap = t2 - t1;

        // 将拷贝时间写入log日志
        ofstream ofs("copyfile.txt", ios::app);
        ofs << gap << endl;     
    }
    finder.Close();

    return 0;
}

参考资料:
string和wstring之间的转换
FindFile FindNextFile 如何遍历一个文件夹并获取里面文件的信息

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值