在Visual Studio Express中使用c++比较两个目录



大家好,

我有一个参考目录和一个目录。我想根据我的参考目录来比较一下这个目录。比较两个文件夹的内容。我将如何能够编码这个?请帮助。非常感谢你的帮助。提前感谢。Bdw,我在Visual Studio Express中使用c++。

对于c++/CLI:

我们需要#include <vcclr.h>转换c++字符串和CLI字符串。改成如下:

#include <vector> 
#include <string> 
#include <windows.h>
int get_files_and_folders(std::wstring dir, std::vector<std::wstring> &fullpath, std::vector<int> &filesize)
{
    if (!dir.size()) return 0;
    if (dir[dir.size() - 1] != '\') dir += L"\";
    WIN32_FIND_DATA find = { 0 };
    std::wstring wildcard = dir + L"*";
    HANDLE hfind = FindFirstFile(wildcard.c_str(), &find);
    if (hfind == INVALID_HANDLE_VALUE)
        return 0;
    do
    {
        std::wstring filename = find.cFileName;
        if (filename == L"." || filename == L"..")
            continue;
        std::wstring path = dir + filename;
        fullpath.push_back(path);
        filesize.push_back(find.nFileSizeLow);
        if (find.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            get_files_and_folders(path, fullpath, filesize);
    } while (FindNextFile(hfind, &find));
    FindClose(hfind);
    return 1;
}
int compare_folders(std::wstring &dir1, std::wstring &dir2, std::wstring &result)
{
    std::vector<int> filesize1, filesize2;
    std::vector<std::wstring> path1, path2;
    if (!get_files_and_folders(dir1, path1, filesize1)) return 0;
    if (!get_files_and_folders(dir2, path2, filesize2)) return 0;
    //test
    for (unsigned i = 0; i < path1.size(); i++)
    {
        System::String^ s = gcnew System::String(path1[i].c_str());
        System::Diagnostics::Trace::WriteLine(s);
    }
    if (path1.size() != path2.size())
    {
        result += L"file + folder count doesn't matchn";
        return 0;
    }
    for (unsigned i = 0; i < path1.size(); i++)
    {
        std::wstring filename1 = path1[i];
        std::wstring filename2 = path2[i];
        filename1.erase(0, dir1.size() + 1);
        filename2.erase(0, dir2.size() + 1);
        if (filename1 != filename2)
        {
            result += L"filename doesn't matchn";
            return 0;
        }
        if (filesize1[i] != filesize2[i])
        {
            result += L"filesize doesn't matchn";
            return 0;
        }
        //todo:
        //open file by fullpath name and compare each bit by bit...?
    }
    result = L"match foundn";
    return 1;
}

现在你可以从CLI

调用这个函数了
//In C++/CLI form: 
#include <vcclr.h>
String^ str1 = L"c:\test1";
String^ str2 = L"c:\test2";
//convert strings from CLI to C++
pin_ptr<const wchar_t> dir1 = PtrToStringChars(str1);
pin_ptr<const wchar_t> dir2 = PtrToStringChars(str2);
std::wstring result;
compare_folders(std::wstring(dir1), std::wstring(dir2), result);
//convert strings from C++ to CLI
System::String^ str = gcnew System::String(result.c_str());
MessageBox::Show(str);

ps,在前面的例子中,我包括了using namespace std;,但它不应该在Forms中。

相关内容

  • 没有找到相关文章

最新更新