Untitled
#include <iostream> #include <sstream> #include <string> #include <vector> #include <unistd.h> #include <map> // Function to read file content using popen std::string read_file(const std::string &path) { std::string command = "cat " + path; FILE *pipe = popen(command.c_str(), "r"); if (!pipe) { std::cerr << "Failed to run command: " << command << std::endl; return ""; } char buffer[128]; std::ostringstream result; while (fgets(buffer, sizeof(buffer), pipe) != nullptr) { result << buffer; } pclose(pipe); return result.str(); } // Function to calculate differences between two sets of lines void compare_and_print_changes(const std::string &previous, const std::string ¤t) { std::istringstream prev_stream(previous), curr_stream(current); std::string line; std::map<std::string, bool> prev_lines, curr_lines; // Populate maps with previous and current lines while (std::getline(prev_stream, line)) { prev_lines[line] = true; } while (std::getline(curr_stream, line)) { curr_lines[line] = true; } // Find added lines std::cout << "Added lines:\n"; for (const auto &entry : curr_lines) { if (prev_lines.find(entry.first) == prev_lines.end()) { std::cout << entry.first << std::endl; } } // Find removed lines std::cout << "Removed lines:\n"; for (const auto &entry : prev_lines) { if (curr_lines.find(entry.first) == curr_lines.end()) { std::cout << entry.first << std::endl; } } } int main(int argc, char *argv[]) { if (argc != 2) { std::cerr << "Usage: " << argv[0] << " <file_path>" << std::endl; return 1; } std::string file_path = argv[1]; std::string previous_content; std::cout << "Monitoring file: " << file_path << std::endl; while (true) { std::string current_content = read_file(file_path); if (current_content.empty()) { std::cerr << "Failed to read file or file is empty: " << file_path << std::endl; sleep(1); continue; } if (!previous_content.empty() && previous_content != current_content) { std::cout << "File changed!" << std::endl; std::cout << "Previous content:\n" << previous_content; std::cout << "Current content:\n" << current_content; compare_and_print_changes(previous_content, current_content); } previous_content = current_content; sleep(1); // Polling interval } return 0; }
Leave a Comment