2

我正在尝试从第二个文件中导出不在第一个文件中的所有行。行的顺序无关紧要,我只想找到那些已经不在第一个文件中的行并将它们保存到differ.txt。

例子:

第一个文件.txt

这是第一行
这是第二行
这是第三行

第二个文件.txt

这是第一行
这是一些行
这是第三行

现在比较一下...

差异.txt

这是一些线


这就是我到目前为止提出的。我知道我需要遍历第二个文件中的所有行并将每一行与第一个文件的每一行进行比较。为什么它不起作用对我来说没有任何意义

void compfiles()
{
    std::string diff;
    std::cout << "-------- STARTING TO COMPARE FILES --------\n";
    ifstream file2;

    file2.open("C:\\\\firstfile.txt",ios::binary);
//---------- compare two files line by line ------------------
    std::string str;
    int j = 0;
    while(!file2.eof())
    {
        getline(file2, str);
        if(!CheckWord(str))
        {
            cout << "appending";
            diff.append(str);
            diff.append("\n");
        }
        j++;
    }
    ofstream myfile;
    myfile.open ("C:\\\\difference.txt");
    myfile << diff;
    myfile.close();
}

bool CheckWord(std::string search)
{
    ifstream file;
    int matches = 0;
    int c = 0;
    file.open("C:\\\\secondfile.txt",ios::binary);
    std::string stringf;
    while(!file.eof())
    {
        getline(file, stringf);
        if(strcmp(stringf.c_str(), search.c_str()))
        {
            matches += 1;
        }
        c++;
    }
    if(matches == 0)
    {
        return false;
    }
    else
    {
        return true;
    }
}

任何帮助,将不胜感激。感谢您阅读此文本块。

4

3 回答 3

3

这段代码没有做你认为它做的事情:

if (strcmp(stringf.c_str(), search.c_str()))
{
    matches += 1;
}

strcmp()当字符串相等时返回 0,但在这种情况下您的代码不会增加 matches

于 2013-06-24T21:37:40.837 回答
3

这是一个使用 std::set 的简单但更有效和惯用的解决方案:

std::ifstream file1("firstfile.txt");
std::set<std::string> str_in_file1;
std::string s;
while (std::getline(file1, s)) { 
    str_in_file1.insert(s);
}
file1.close();
std::ifstream file2("secondfile.txt");
std::ofstream file_diff("diff.txt");
while (std::getline(file2, s)) { 
    if (str_in_file1.find(s) == str_in_file1.end()) {
        file_diff << s << std::endl;
    }
}
file2.close();
file_diff.close();

此外,您可能想要使用一个名为diff的工具。它完全符合您的要求。

于 2013-06-24T21:31:22.273 回答
0

如果您想手动执行此操作,那么听起来您不需要 c++ 程序,但您可以使用 grep 从命令行执行此操作。

grep -vxFf firstfile.txt secondfile.txt > difference.txt
于 2013-06-24T23:04:18.727 回答