The problem was a malformed regex, the rest of the code works.
Search for a string in a binary file with C++
-
19-07-2023 - |
Вопрос
I wrote a short program to search for a string in a binary file. The file consists of text and Base64 content. If I test it with an ASCII text file, it works. If I try it with a binary file, it does not match anything.
So can you tell me:
- Where's my fault?
- What is the best (computational) way to search for a string in a binary file?
UPDATE: A direct string comparison works, so the problem has to be somewhere in the regex definition.
Code
19 #include<iostream>
20 #include<fstream>
21 #include<regex>
22 #include<string>
23
24 using namespace std;
25
26 int main(int argc, char* argv[]) {
27 if (argc != 2){
28 cout << "Error message";
29 }
30
31 regex type_response ("(TEST: )(.*)");
32 regex target_value ("(VALUE: )(.*)");
33 regex target_version ("(NAME: )(.*)");
34
35 ifstream infile(argv[1], ios::binary);
36
37 if (infile.is_open()){
38 string line;
39 while (getline(infile, line)){
40 if (regex_match(line ,target_version)){
41 cout << line;
42 }
43 };
44 infile.close();
45
46 return 0;
47 }
48
49 else {
50 cout << "Could not open file.\n";
51 return 1;
52 };
53 };
Решение 2
Другие советы
An ASCII file is a binary file that stores ASCII codes and an ASCII code is a 7-bit code stored in a byte. While a binary file has no such restrictions and any of the 8 bits can be used in any byte of a binary file.
In ASCII file the highest bit of each byte is not used and it means the highest bit is treated as 0. While in binary file, it maybe 0 or 1. So there are difference. You can check the hex detail of the binary file using tools like HxD.