Project 2
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const string logFileName = "can_log.txt";
const string keptLogFileName = "kept_log.txt";
const string tempLogFileName = "temp_log.txt";
// Function to prompt user for signal search
string promptForSignal() {
string signal;
cout << "Enter signal to search for: ";
cin >> signal;
return signal;
}
// Function to perform binary search
void binarySearch(const string& signal) {
ifstream logFile(logFileName);
ofstream keptLogFile(keptLogFileName), tempLogFile(tempLogFileName);
// Copy contents of log file to kept log file
keptLogFile << logFile.rdbuf();
while (true) {
int numMessages = 0;
string line;
// Count number of messages in kept log
ifstream keptLogFile(keptLogFileName);
while (getline(keptLogFile, line)) {
++numMessages;
}
keptLogFile.close();
// Display number of remaining messages
cout << "Remaining messages: " << numMessages << endl;
// Prompt user to check if signal occurred again
char answer;
cout << "Did the signal occur again? (Y/N): ";
cin >> answer;
// If signal occurred again, move kept log to temp log
if (answer == 'Y' || answer == 'y') {
ifstream keptLogFile(keptLogFileName);
ofstream tempLogFile(tempLogFileName);
tempLogFile << keptLogFile.rdbuf();
keptLogFile.close();
tempLogFile.close();
}
// If only one message remains, signal found
if (numMessages == 1) {
cout << "Signal found in message: " << line << endl;
break;
}
// Split kept log file in half and search appropriate half
ifstream keptLogFile(keptLogFileName);
ofstream logFile(logFileName);
int splitPoint = numMessages / 2;
int count = 0;
while (count < splitPoint && getline(keptLogFile, line)) {
logFile << line << endl;
++count;
}
keptLogFile.close();
logFile.close();
// If signal found in first half, keep first half, else keep second half
keptLogFile.open(keptLogFileName);
tempLogFile.open(tempLogFileName);
bool signalFound = false;
while (getline(keptLogFile, line)) {
if (line.find(signal) != string::npos) {
signalFound = true;
break;
}
tempLogFile << line << endl;
}
keptLogFile.close();
tempLogFile.close();
if (signalFound) {
remove(keptLogFileName.c_str());
rename(tempLogFileName.c_str(), keptLogFileName.c_str());
} else {
remove(keptLogFileName.c_str());
rename(logFileName.c_str(), keptLogFileName.c_str());
}
}
}
int main() {
string signal = promptForSignal();
binarySearch(signal);
return 0;
}