Shantanu Jain Shantanu Jain -4 years ago 165
C++ Question

Counting the frequency of hex characters in a .txt file

I have a file that contains hexadecimal values separated by spaces. I want to find the frequency of each of the hex values and write it to a text file. For example, consider the string

"1b 17 3c 45 3f 52 7a 5a 3b 45 31 52 2e 17 3e 58 3f 44 "
. I want to count the frequency of occurrence of each hex value:

1b - 1 times
17 - 2 times
.... so on.


I have currently written a c++ program but it counts the space between the hex characters as a hex character as well and does not function as expected.

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>

using namespace std;

int main()
{
int x = 0;
int total[128] = {0};
int index;

ifstream infile;
ofstream outfile;

infile.open("hex.txt");
outfile.open("results2.txt");
if(!infile)
{
cout << "Error opening input file" << endl;
return 0;
}

char c;
while(infile.get(c))
{
index = c;
total[index]++;
}

for (int i=0; i<128; i++) // Print the results
{
outfile << " " << hex << i << " occurs "
<< setw(5) << dec << total[i] << " times"
<< " " << endl;
}
return 0;
}


Note:

"hex.txt" is the input file
"results2.txt" is the output file

Answer Source

Simply read the input file as hex:

while(infile >> hex >> index)
{
    if (index < 0 || index >= 128) {   // ensure value is in array range...
        cerr << "Found an incorrect value " << hex << index << endl;
        return 1;
    }
    total[index]++;
} 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download