Hi.

I want to read a file and scan the file to see if the file contains 0x000001 (24 bits, 23 zero and 1 one bit). if file contains 0x000001, return a "yes", else return a "no".

I tried writing the program but cannot work. I am stuck with this for several days already.

This is an incomplete program. Can you pls help me out with this?

Thank you very much.

#include <iostream>
#include <fstream>
#include <stdio.h>

using namespace std;
int main() {
      std::ifstream ifs("c:\\FT_student.pdf", std::ios::binary);
      char buff[1024];
      ifs.seekg (0, std::ios::beg);
      int count = 0;
      while(!ifs.eof()){
                        ifs.getline(buff,1024);
                        std::cout << count++ << std::endl;
                        }

    cin.ignore();
    cin.get();
    return 0;
}

What will the contents of the file be like? You can try something like this:

i assume they are on new lines. So, is it 4bytes, separated by a newline character?

So, you can read 4 bytes. Read it into a buffer. say

unsigned char buff[4];

Now, check for your required condition using the >> operator.
Scan through all the bits.

OR

Another option would be to use bitset.

A binary file may contain multiple eof characters. So take the size of the file and loop to the total size / till you find the required binary number.

First create a user defined type to represent 23 zero bits and 1 one bit.

#include <cstdint> // C++1X (or <stdint.h> for C99)
struct pattern
{
    enum { NBYTES = 3 } ;
    std::uint8_t bytes[NBYTES] ; // 3 x 8 bits == 24 bits
};

Then provide mechanisms to read such a variable from an input stream and to compare two such variables for equality.

std::istream& operator>> ( std::istream& stm, pattern& p )
{ return stm.read( reinterpret_cast<char*>( p.bytes ), pattern::NBYTES ) ; }

bool operator== ( const pattern& first, const pattern& second )
{ return std::equal( first.bytes, first.bytes + pattern::NBYTES, second.bytes ) ; }

Finally, write the function to return a "yes" or a "no"

const char* find_pattern( const char* path_to_file )
{
    std::ifstream file( path_to_file, std::ios::binary ) ;
    std::istream_iterator<pattern> begin(file), end ;
    static const pattern search_pattern = { { 0, 0, 1 } } ; // 23 zero bits and 1 one bit
    return std::find( begin, end, search_pattern ) == end ? "no" : "yes" ;
}
commented: Helpful advise. Thanks a lot! +2

Hi all,
thanks for your help. i will try to do it again with all of your guidance. Thanks again.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.