I have to create a function that checks if a specific word exists in the .bin file. I want to use the binary search algorithm. The thing is, I have to read from a .bin file, so I got confused (like there are no lines, right?). Function does not work for me. It states that the “specific word” (entered by the user) does not exist, although it does exist. Any help would be enjoyable.
#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
#include <algorithm>
using namespace std;
const int buffer_size = 30;
void Create_Bin_File ()
{
ifstream fin ("example.txt");
ofstream fout ("Binary.bin", ios::binary);
const unsigned int RECORD_SIZE = 30;
char buffer[RECORD_SIZE] = {0};
while (fin.getline (buffer, RECORD_SIZE))
{
fout.write (buffer, RECORD_SIZE);
fill_n (buffer, RECORD_SIZE, 0);
}
fin.close ();
fout.close ();
}
void Binary_Search (const string& filename, string SearchVal)
{
ifstream file (filename.c_str(), ios::binary);
if (file.is_open())
{
cout << "The file is opened"<< endl;
cout << "\n";
}
else
{
cout << "Error opening file"<< endl;
cout << "\n";
return;
}
const unsigned int RECORD_SIZE = 30;
char buffer[RECORD_SIZE] = {0};
int recordCount = 0;
int recordWanted = -1;
while (file.read(buffer, RECORD_SIZE))
{
if(SearchVal == buffer)
{
recordWanted = recordCount;
}
cout << recordCount << " : " << buffer << "\n";
fill_n (buffer, RECORD_SIZE, 0);
++recordCount;
}
cout << "\n";
cout << "file contains " << recordCount << " records\n";
cout << "\n";
if (recordWanted == -1)
cout << "record wanted could not be found\n";
else
cout << "record wanted is at index " << recordWanted << " records\n";
cout << "\n";
}
int main()
{
Create_Bin_File();
string word;
cout << "Enter word, that you want to find in a file: " << endl;
cin >> word;
Binary_Search("Binary.bin", word);
return 0;
}
:
" ++. , . - .
H7. , ++ ( , , , ). , , , , ( 30) ++ . . ++ . "
grek40 BinarySearch:
, :
std::string GetRecord(std::ifstream& inFile, int pos)
{
char buffer[RECORD_SIZE];
inFile.clear();
inFile.seekg(pos * RECORD_SIZE, std::ios::beg);
inFile.read(buffer, RECORD_SIZE);
return buffer;
}
: ( - !)
void Binary_Search (const string& filename, string SearchVal)
{
ifstream file (filename.c_str(), ios::binary);
if (file.is_open())
{
cout << "The file is opened"<< endl;
cout << "\n";
}
else
{
cout << "Error opening file"<< endl;
cout << "\n";
return;
}
int pos = 0;
int lowerLimit = 0;
int recordCount = 73;
char buffer[RECORD_SIZE] = {0};
int upperLimit = recordCount;
while ( (lowerLimit < upperLimit) )
{
pos = (lowerLimit + upperLimit) / 2;
std::string buffer = GetRecord(file, pos);
if (buffer == SearchVal)
{
cout << "Found!";
lowerLimit = 1;
upperLimit = 0;
}
else if (SearchVal > buffer)
{
lowerLimit = pos + 1;
}
else if (SearchVal < buffer)
{
upperLimit = pos;
}
}
}