R
R
rusianvodka2014-05-20 23:45:27
C++ / C#
rusianvodka, 2014-05-20 23:45:27

Finding a number in a file opened in binary mode?

Hello ladies and gentlemen, a question arose about finding a number in a binary file.
Let's say we have a code:

#include <iostream>
#include <conio.h>
using namespace std;
void main(){
  int t = 247;
  t = t - 246;
  cout << t << endl;
  _getch();
}

This code is compiled and executed, it produces an .exe file.
I open this .exe file with hiew32(hex - editor) and can easily find the number 247 to change it. After the .exe file will display a different result (depending on the change).
The question arose of how to carry out this search for a given number in C++ code.
Googling and reading the literature, I got this solution:
ifstream file_op(m_FileIn, ios::binary);
  if (!file_op) return 0;
   int buf[1024];
   int a = 247;     // то  что мы ищем
   int z = 0;		// счётчик поиска
   do {
     file_op.read((char *)buf, sizeof buf);
     for (int i = 0; i < 256; i++)
     {
       if (buf[i] == a) 
         z++;	// счётчик(после полного прохода по файлу должен быть равен 1.)
     }
 	 
   } while (!file_op.eof());
   file_op.close();
  return false;

But unfortunately this code is not executed as intended.
I would be grateful for corrections and instructions. And solutions to the problem of inoperability of this code.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Eugene Sokolov, 2014-05-21
@VirtualSnake

ifstream file_op( "test.exe", ios::binary );
if( !file_op )
{
  cout << "Not found!" << endl;
  return 0;
}
file_op.seekg( 0, file_op.end );
int length = file_op.tellg();
file_op.seekg( 0, file_op.beg ); // считаем длину файла
int8_t *buf = new int8_t[ length ];
int a = 247; // то  что мы ищем
bool find = false;
int position = 0;
file_op.read( (char *)buf, length );
for( int i = 0; i < length; i++ )
{
  if( *reinterpret_cast<int32_t*>( buf + i ) == a )
  {
    cout << "Founded in " << i << " position" << endl;
  }
}
delete[] buf;
file_op.close();

R
rusianvodka, 2014-05-21
@rusianvodka

ifstream file_op(m_FileIn, ios::binary);
  if (!file_op) return 0;
  int v = 0;
  int buf[256];
   int a = 247; // то  что мы ищем
   int z = 0;		// счётчик, нашёл ли то что мы ищем
   do {
    file_op.read((char *)buf, sizeof buf);
    for (int i = 0; i < 256; i++)
     {
       if (buf[i] == a) 
         z++;	
     }
   } while (!file_op.eof());
   file_op.close();
   return false;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question