2013-07-09 42 views
0

我不明白爲什麼這是輸出一個不同的文件,因爲輸入文件的開始匹配第一個if語句。另外,如果有多個發現,則下一個文件名將成爲最後的文件名和新的文件名。C++讀文件,搜索十六進制,輸出文件

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; 
} 
+2

'stringstream.clear()'不空流,它只是重置一些標誌。改用'stringstream.str(「」)'。 –

+0

這解決了文件名問題。 – Marc05

回答

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; 
    } 
}