令人恐惧的提示

问题描述 投票:0回答:2

我开始学习C,但是我已经对fread();函数有一些问题:

我有一个文件,我需要在循环中每4个字节读取它(像这样):

#define defined "\x02\xA1\xC0\xD1" // given by other student

int main(int argc, char *argv[]){
  FILE *f = fopen(argv[1], "rb");
  if(!fd){ return -1; }

  // get the size of our file
  fseek(f,0,SEEK_END);

  int len = ftell(f);
  fseek(f,0,SEEK_SET);
  char* file = malloc(len);
  fread(file,len,1,f);

  fclose(f); // useless here apparently ?

  for(int x=0; x<len; x+=4){
    if(memcmp(file+x,defined,4)==0) { // compare every 4bytes until find the defined in the file
      printf("%p",x);
  }
  return(0);
}

我已经阅读了MAN,但是不确定自己在做什么:-/

谢谢

c arrays file bit
2个回答
0
投票
[应尽可能避免寻找文件的末尾以获取其长度,因为它使程序无法与管道输入一起使用。

而是考虑每次调用读取许多4字节对象的块。这减少了读取开销,并允许使用管道。 fread将通过返回比请求少的项目来告诉您何时到达输入结尾。

#include <stdint.h> #include <stdio.h> int main(int argc, char *argv[]) { FILE *f = fopen(argv[1], "rb"); if (!f) return -1; const int chunk_size = 1000; uint32_t buf[chunk_size]; // a chunk of data read from the input in one fread() size_t n_read; do { n_read = fread(buf, sizeof buf[0], chunk_size, f); // reads a chunk of ints for (int i = 0; i < n_read; ++i) printf("%u\n", buf[i]); // prints what was read } while (n_read == chunk_size); // stops when end of input is reached return 0; }


0
投票
我认为您使代码变得比给定规范所需的复杂。当然,在fclose(f)之后,您不能指望fread(file, 4, 1, f)有任何用处-如果您检查了返回值,则返回0表示失败。
© www.soinside.com 2019 - 2024. All rights reserved.