C ++读取文件,搜索十六进制,输出文件

时间:2013-07-09 16:26:54

标签: c++ search file-io hex

我无法弄清楚为什么输出文件的开头与第一个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;
}

1 个答案:

答案 0 :(得分: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;
    }
}