计算C中给定文件中所有字节的平均值

标签 c

我写了程序,但找不到问题所在。它读取文件很好,但给出的结果是 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/

相关文章:

c - 通过示例了解限制限定符

c - 在 C 中回显所有回文

c - fopen() 在一段时间内成功打开文本文件并在特定时间后失败

c - Valgrind:大小 1 的无效读取

c lang - 通过指针不同的数组长度

C - 编译程序时出现多个警告 "pointer is missing a nullability type specifier",我该怎么办?

c - 如何在 C 语言中使用 uint64_t

密码加密解密逻辑

c - gcc 的 __attribute__((packed))/#pragma pack 不安全吗?

c 内联汇编字符数组转短