i think i have a stupid mistake in my code but can't find it.
I try to read a Binary file and scan every 4 bytes for a certain pattern to break a big file apart.
std::string* filename = new std::string((args > 1?argv[1]:"data.bin"));
std::cout << filename;
int filenumber = 0;
std::ifstream myfile (*filename, std::ios::binary);
if (myfile.is_open())
{
bool newfile = true;
std::streampos filebegin = 0;
std::streampos fileend = 0;
char* buffer = new char[4];
int oldpos = -1;
while ( myfile.good() )
{
myfile.get(buffer,4); // get character from file
int currpos = myfile.tellg();
// std::cout << currpos << std::endl;
if (myfile.good() && buffer[0] == 82 && buffer[1] == 73 && buffer[2] == 70 && buffer[3] == 70){
if(newfile){
newfile = false;
filebegin = myfile.tellg()-std::streampos(3);
std::cout << "file begin" << std::endl;
}
else{
newfile = true;
fileend = myfile.tellg()-std::streampos(4);
char* filebuffer = new char[fileend-filebegin];
myfile.seekg(filebegin);
myfile.get(filebuffer,fileend-filebegin);
std::ostringstream os;
os << "file" << filenumber << ".bin";
std::ofstream myofile (os.str());
filenumber++;
if (myofile.is_open()){
std::cout << "file " << filenumber << std::endl;
myofile << filebuffer;
}
myofile.close();
delete[] filebuffer;
}
}
myfile.seekg(myfile.tellg()-std::streampos(2));
oldpos = currpos;
}
myfile.close();
}
else std::cout << "Unable to open file";
But after some loops it got stuck on position 3387.
Does some one know what I do wrong?
I use TDM-GCC to compile. edit: It does not even get to the pattern I search.
greetings Wasabi
Perhaps you should replace
myfile.get(filebuffer,fileend-filebegin);
with
myfile.read(filebuffer,fileend-filebegin);
and try again. The reason was already explained by @uesp.