I have a file. I read the size of file. Then I loop reading two bytes at a time until I get to the end of the file. After every read operation I increment the current position by 2, however the position does not get incremented after I get to half the size of the file, the fread operation will read 0 bytes.
the program reads the file size. I perform fread (2 bytes everytime) until the current position is equal to the size of the file.
It reads 22915 byes for the file size
It increments position by 2 after every read, however when current position gets to 11459 which is half the size of the file it will read zero bytes thus going into an infinite loop.
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;
}
This statement reads two items of two bytes each. And it returns the value 2, for the number of items read. The second and third parameters multiplied together tell
freadhow many bytes to read.