Compare two files

前端 未结 6 1631
一向
一向 2020-12-14 03:57

I\'m trying to write a function which compares the content of two files.

I want it to return 1 if files are the same, and 0 if different.

ch1 an

6条回答
  •  执笔经年
    2020-12-14 04:34

    Here's a C++ solution. It seems appropriate since your question is tagged as C++. The program uses ifstream's rather than FILE*'s. It also shows you how to seek on a file stream to determine a file's size. Finally, it reads blocks of 4096 at a time, so large files will be processed as expected.

    // g++ -Wall -Wextra equifile.cpp -o equifile.exe
    
    #include 
    using std::cout;
    using std::cerr;
    using std::endl;
    
    #include 
    using std::ios;
    using std::ifstream;
    
    #include 
    using std::exception;
    
    #include 
    #include 
    using std::exit;
    using std::memcmp;
    
    bool equalFiles(ifstream& in1, ifstream& in2);
    
    int main(int argc, char* argv[])
    {
        if(argc != 3)
        {
            cerr << "Usage: equifile.exe  " << endl;
            exit(-1);
        }
    
        try {
            ifstream in1(argv[1], ios::binary);
            ifstream in2(argv[2], ios::binary);
    
            if(equalFiles(in1, in2)) {
                cout << "Files are equal" << endl;
                exit(0);
            }
            else
            {
                cout << "Files are not equal" << endl;
                exit(1);
            }
    
        } catch (const exception& ex) {
            cerr << ex.what() << endl;
            exit(-2);
        }
    
        return -3;
    }
    
    bool equalFiles(ifstream& in1, ifstream& in2)
    {
        ifstream::pos_type size1, size2;
    
        size1 = in1.seekg(0, ifstream::end).tellg();
        in1.seekg(0, ifstream::beg);
    
        size2 = in2.seekg(0, ifstream::end).tellg();
        in2.seekg(0, ifstream::beg);
    
        if(size1 != size2)
            return false;
    
        static const size_t BLOCKSIZE = 4096;
        size_t remaining = size1;
    
        while(remaining)
        {
            char buffer1[BLOCKSIZE], buffer2[BLOCKSIZE];
            size_t size = std::min(BLOCKSIZE, remaining);
    
            in1.read(buffer1, size);
            in2.read(buffer2, size);
    
            if(0 != memcmp(buffer1, buffer2, size))
                return false;
    
            remaining -= size;
        }
    
        return true;
    }
    

提交回复
热议问题