0

鉴于输入文件的开头与第一个 if 语句匹配,我无法弄清楚为什么会输出不同的文件。此外,如果有多个查找,则下一个文件名将是最后一个文件名加上新文件名。

int main()
{
    unsigned short n(0);
    unsigned char y;

    std::ostringstream filename;

    std::ifstream input("data.dat", std::ios::binary);
    input >> std::noskipws >> std::hex;

    std::ofstream output;
    output << std::ios::binary;

    while (input.good()) {
        filename.clear();
        filename << n << ".dat";
        output.open(filename.str());
        while ( input.good() )
        {
            input >> y;
            output << y;
            if ( y == 0xFF ) {
                input >> y;
                output << y;
                if ( y == 0xD9 ) {
                    input >> y;
                    output << y;
                    output.close();
                    break;
                }
            }
        }
        if (output.is_open())
            output.close();
        ++n;
    }
    return 0;
}
4

1 回答 1

0
#include <iostream>  // for input/output
#include <fstream>   // for file stream stuff
#include <sstream>   // for ostringstream

int main()
{
    unsigned short nFile = 0;  // used to increment file name

    std::ostringstream filename;  // output filename

    std::ifstream inFile;      // input stream
    std::ofstream outFile;     // output stream
    unsigned char buffer;      // buffer between input and output

    inFile.open("data.dat", std::ios::binary);  // open input file
    if ( inFile.fail() )
        return 1;

    while ( inFile.good() )
    {
        filename.str("");             // empties the stream
        filename << nFile << ".dat";  // generate filename

        // start the search loop
        while ( inFile.good() )
        {
            // create a file
            outFile.open(filename.str(), std::ios::binary);
            if ( outFile.fail() )
                return 1;

            while ( inFile.good() )
            {
                inFile.read(reinterpret_cast<char*>(&buffer), sizeof(buffer));  // read a byte
                if ( inFile.eof() )
                    break;
                outFile.write(reinterpret_cast<char*>(&buffer), sizeof(buffer));  // write a byte
                if ( buffer == 0xFF )
                {
                    inFile.read(reinterpret_cast<char*>(&buffer), sizeof(buffer));  // read a byte
                    if ( inFile.eof() )
                        break;
                    outFile.write(reinterpret_cast<char*>(&buffer), sizeof(buffer));  // write a byte
                    if ( buffer == 0xD9 )  // full match; break loop
                    {
                        break;
                    }
                }
            }
            // if search is done and file is still open, close it
            if (outFile.is_open())
                outFile.close();
            ++nFile;
        }
        return 0;
    }
}
于 2013-07-11T13:09:58.973 回答