1
我很困惑如何使用fread()
。下面是cplusplus.comfread后访问内存缓冲区()
/* fread example: read a complete file */
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE * pFile;
long lSize;
char * buffer;
size_t result;
pFile = fopen ("myfile.bin" , "rb");
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
// allocate memory to contain the whole file:
buffer = (char*) malloc (sizeof(char)*lSize);
if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
// copy the file into the buffer:
result = fread (buffer,1,lSize,pFile);
if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
/* the whole file is now loaded in the memory buffer. */
// terminate
fclose (pFile);
free (buffer);
return 0;
}
一个例子比方说,我不使用fclose()
只是还没有。我现在可以将buffer
作为一个数组并访问像buffer[i]
这样的元素吗?还是我必须做别的事情?
当我在二进制文件中读取时,每个元素的类型是什么?我有一种感觉,在这种情况下,他们都是'char'。他们都必须是同一类型吗?因为我有一些双打和一些十六进制值。感谢您的回答。 – 2012-04-05 23:32:56
关于二进制文件的好处是,如果你知道确切的布局,你不会有任何问题,你可以定义一个结构,在该文件内具有相同布局的二进制数据,并且(如果字节顺序是正确的)直接获得数据准备好使用。检查我的编辑。 – Jack 2012-04-05 23:34:28