在C中使用fread时无法读取二进制文件

时间:2019-10-22 19:02:37

标签: c binary fread

我在使用C中的fread读取二进制数据时遇到问题。

这是我需要读取的二进制文件。

https://i.stack.imgur.com/7qfK6.png

我的问题是该文件在5行中包含普通文本,我无法弄清楚如何避免它们或将它们读取为文本,以及当二进制部分开始读取二进制数据时。

这是我的代码:

size_t num;
FILE *fp = fopen("binaryXYZRGB.nkt", "rb");

if(fp == NULL){
    printf("HATA!!!\n");
    exit(1);
}

int counter = 0;
while(1){

    struct read a;
    num = fread(&a, 1, sizeof(a), fp);
    printf("%d-) %f %f %f %d %d %d\n", counter, a.x, a.y, a.z, a.r, a.g, a.b);

    counter++;

    if(num < 1){
        break;
    }
}

并阅读结构:

struct read{
 float x;
 float y;
 float z;
 int r;
 int g;
 int b;  
};

我可能读过这样的内容

https://i.stack.imgur.com/ZYUbY.png

但是我读到了

https://i.stack.imgur.com/fbaqd.png

如果有人可以帮助我,那就太好了。

1 个答案:

答案 0 :(得分:0)

正如我在屏幕截图中所看到并得到您的确认,您在二进制数据之前有5行普通数据... 我们提供了两种选择...都涉及将“ fgets”与“ fread”一起使用。.

“ fgets”,因为它会停止并且在遇到时还会记录新行。这使我们能够在使用“ fread”读取二进制数据之前准确定位文件指针。 几个文件指针定位选项是

  • “ ftell”和“ fseek”

    OR

  • “ fgetpos”和“ fsetpos”

下面的代码记录了这两种方法,但是我使用了“ fgetpos”和“ fsetpos”。 希望这些评论有用。

#include <stdio.h>

int main(){
int n = 0; //to use in "ftell"
int i = 0; //as a counter
FILE * fp;
char array[100];//in case you want to store the normal characters received from "fgets"
fpos_t ptr;//used to record file pointer position in fgetpos and fsetpos
size_t num;

FILE *fp = fopen("binaryXYZRGB.nkt", "rb");

while(i < 5){//since there are 5 lines
  fgets(array+n,sizeof array,fp);//stores these lines in array
//n = ftell(fp);//use this with fseek, post 5 iterations "n" would be the offset 
  i++;          // of binary data from the start of the file.
}               

//fseek(fp,n,SEEK_SET);//can use this instead of fgetpos/fsetpos
                     //the offset "n" collected above is used
//printf("%s",array);//if array needs to be printed

fgetpos(fp,&ptr);//get the current position of the file pointer   
fsetpos(fp,&ptr);//set the current position of the file pointer

int counter = 0;
while(1){

  struct read a;
  num = fread(&a, 1, sizeof(a), fp);
  if(num < 1){ //have brought the break condition above the print statement
    break;
  }
  printf("%d-) %f %f %f %d %d %d\n", counter, a.x, a.y, a.z, a.r, a.g, a.b);
  counter++;

}
 fclose(fp);
}
相关问题