我有一个文件。我读了文件的大小。然后我一次循环读取两个字节,直到到达文件末尾。每次读取操作后,我都会将当前位置增加 2,但是当我达到文件大小的一半后位置不会增加,fread 操作将读取 0 个字节。
程序读取文件大小。我执行 fread(每次 2 个字节)直到当前位置等于文件的大小。 文件大小为 22915 字节 它在每次读取后将位置增加 2,但是当当前位置达到 11459(文件大小的一半)时,它将读取零字节,从而进入无限循环。
FILE *file;
char *file_name;
int readCount = 0;
int position = 0;
int fileSize;
unsigned short mem_accesses;
file_name = "sample.txt";
/** open the file */
file = fopen(file_name, "rb");
fseek(file, 0, SEEK_END);
fileSize = ftell(file);
rewind(file);
while(position<fileSize){
mem_accesses = getNumberAccesses();
printf("position: %d filesize: %d\n",position, fileSize);
}
unsigned short getNumberAccesses(){
/** calculate number of accesses for process */
unsigned short val;
readCount = fread(&val, sizeof(val), 2, file);
position += readCount;
printf("read count: %d\n", readCount);
return val;
}
最佳答案
readCount = fread(&val, sizeof(val), 2, file);
此语句读取两个项目,每个项目两个字节。并且它返回值 2,表示读取的项目数。第二个和第三个参数相乘告诉 fread
要读取多少字节。
关于C编程ftell fseek fread,读取文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1843850/