我写了程序,但找不到问题所在。它读取文件很好,但给出的结果是 0。我在传递文件指针时做错了什么吗?
#include <stdio.h>
unsigned char average(const char *filename){
unsigned int BLOCK_SIZE=512;
unsigned int nlen=0, nround=0;
unsigned char avg = 0;
FILE *fp;
unsigned char tmp[512];
if ( (fp = fopen(filename,"r")) == NULL){
printf("\nThe file did not open\n.");
return 500;
}
while(!feof(fp)){
if(fread(tmp, 1, BLOCK_SIZE, fp)){
nlen+=BLOCK_SIZE;
nround++;
}else{
BLOCK_SIZE=BLOCK_SIZE/2;
}
}
avg=(unsigned char)(nlen/nround);
return avg;
}
int main(void){
printf(" The average of all bytes in the file : %d \n" ,average("v") );
return 0;
}
`
最佳答案
OP的代码大致计算BLOCK_SIZE
计数。 @Groo
1) 将所有字符的总和一一相加,然后然后相除。使用宽整数类型。
unsigned long long sum = 0;
unsigned long long count = 0;
...
sum += tmp[i];
count++;
2) feof(fp)
在文件结束或发生读取失败之后很有用。不要使用 to 来确定是否存在另一个字符。检查 fread()
结果。
size_t read_count = fread(tmp, 1, BLOCK_SIZE, fp);
if (read_count == 0) Done();
3) 对于返回 unsigned char
的函数来说,返回 500 没有什么意义。使用int
4) 避免除以 0。
5)完成后关闭文件。
6) 以二进制模式打开。 @Anders K.
// avg=(unsigned char)(nlen/nround);
if (nround) avg=(unsigned char)(nlen/nround);
放在一起
#include <stdio.h>
#include <stdlib.h>
int average(const char *filename){
FILE *fp = fopen(filename,"rb");
if (fp == NULL){
printf("\nThe file '%s' did not open\n.", filename);
return -1;
}
unsigned long long n = 0;
unsigned long long sum = 0;
unsigned char tmp[512];
size_t read_count;
while((read_count = fread(tmp, 1, sizeof tmp, fp)) > 0) {
n += read_count;
for (size_t i = 0; i<read_count; i++) {
sum += tmp[i];
}
}
fclose(fp);
int avg = 0;
if (n) {
avg = (int) (sum/n);
}
return avg;
}
关于计算C中给定文件中所有字节的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38666719/