【发布时间】:2014-09-23 00:19:15
【问题描述】:
我正在尝试查找任何给定文件的熵。但是,当我运行我的程序时,它总是给出 3.00000 作为答案。我有一段时间没有使用 C,但我不确定我在哪里出错了。我已经摆弄了几个小时了。任何提示都会很棒,谢谢!
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#define SIZE 256
int entropy_calc(long byte_count[], int length)
{
float entropy;
float count;
int i;
/* entropy calculation */
for (i = 0; i < SIZE; i++)
{
if (byte_count[i] != 0)
{
count = (float) byte_count[i] / (float) length;
entropy += -count * log2f(count);
}
}
return entropy;
}
int main(int argc, char **argv)
{
FILE *inFile;
int i;
int j;
int n; // Bytes read by fread;
int length; // length of file
float count;
float entropy;
long byte_count[SIZE];
unsigned char buffer[1024];
/* do this for all files */
for(j = 1; j < argc; j++)
{
memset(byte_count, 0, sizeof(long) * SIZE);
inFile = fopen(argv[j], "rb"); // opens the file given on command line
if(inFile == NULL) // error-checking to see if file exists
{
printf("Files does not exist. `%s`\n", argv[j]);
continue;
}
/* Read the whole file in parts of 1024 */
while((n = fread(buffer, 1, 1024, inFile)) != 0)
{
/* Add the buffer to the byte_count */
for (i = 0; i < n; i++)
{
byte_count[(int) buffer[i]]++;
length++;
}
}
fclose(inFile);
float entropy = entropy_calc(byte_count, length);
printf("%02.5f \t%s\n", entropy, argv[j]);
}
return 0;
}
【问题讨论】:
-
在
entropy_calc内,entropy未初始化。 -
编译所有警告和调试信息 (
gcc -Wall -g) - 这应该会给你一个关于你的错误的很好的警告。 使用调试器 (gdb) -
我看不到您在
main中初始化length的位置。您需要检查所有变量,并确保在使用它们之前对其进行初始化。一个好的编译器应该警告你。 -
关于“文件的熵”,您可能会发现this answer 是一个有趣的读取(TL;DR: 一个文件(或一组固定的字节)不有熵。)
-
非常感谢大家,只是为了说明已经过了多久。我混淆了声明和初始化值,返回类型错误。现在一切都很好,再次感谢。