Connecting Tech Pros Worldwide Forums | Help | Site Map

Search for a string in a binary file format

Newbie
 
Join Date: Oct 2006
Posts: 21
#1: Oct 24 '06
Hi ,

I have a binary file which contains 30,000 strings of 20 bytes each.I need to search for a string in the file to see whether the particular string exists.

The sample code which i wrote to write a single string to binary file is :

#include <iostream>
#include <fstream>

int main () {
ofstream os;
char obuffer[20]={"A0000000000"};
os.open ("test.txt", ios::ate|ios::out |ios::binary );

os.write((char*)(&obuffer),sizeof(obuffer));

os.close()}

Now to read the string back from the binary file :

#include <iostream>
#include <fstream>

int main () {
char buffer[20];

ifstream is;
is.open ("test.txt",ios::in|ios::binary );

is.seekg (0,ios::beg);
is.read ((char*)(&buffer),sizeof(buffer));

while(!is.eof()){
cout << buffer<<endl;
is.read ((char*)(&buffer),sizeof(buffer));
}


This works fine.But how to implement a traversal routine which will search for a particular string in the file.



Banfa's Avatar
AdministratorVoR
 
Join Date: Feb 2006
Location: South West UK
Posts: 6,166
#2: Oct 24 '06

re: Search for a string in a binary file format


Err, it's the same as what you have except that instead of outputing the read value every time you check to see if it is the required value.
Reply