将所有代码写在主函数中:打开一个任意类型的文件,统计每种字节(0 - 255)的出现次数,按字节值从小到大的顺序,输出出现次数大于0的字节值及对应的出现次数。
代码如下,如有帮助,请采纳一下,谢谢。
#include <stdio.h>
#include <map>
using namespace std;
int main()
{
FILE *fp =NULL;
long n = 0;
if ((fp = fopen("Q.txt","r")) == NULL)
{
printf("文件打开失败。\n");
return 0;
}
fseek(fp,0,SEEK_END); //指针:移动到文件尾部
n = ftell(fp); //返回指针偏离文件头的位置(即文件中字符个数)
rewind(fp);
char *buf = new char[n+1];
n = fread(buf, 1, n, fp);
fclose(fp);
map<char,long> mapInfo;
map<char,long>::iterator it ;// mapInfo;
for (int i = 0; i < n; i++)
{
it = mapInfo.find(buf[i]);
if (it == mapInfo.end())
{
mapInfo.insert(pair<char,long>(buf[i],1));
}else
{
long ll = it->second;
ll += 1;
mapInfo.erase(it);
mapInfo.insert(pair<char,long>(buf[i],ll));
}
}
//dayin
for (it = mapInfo.begin(); it != mapInfo.end(); it++)
{
printf("%d:%ld\n",it->first,it->second);
}
getchar();
getchar();
return 0;
}