views:

2677

answers:

2

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;
}
+5  A: 

readCount = fread(&val, sizeof(val), 2, file);

This statement reads two items of two bytes each. And it returns two, for the number of items read. The second and third parameters multiplied together tell fread how many bytes to read.

Matthias Wandel
+1 for spotting that
Yacoby
thanks. i chaged sizeof(val) to sizeof(char)thanks
@OP: You should have changed `...sizeof(val),2...` to `...1,sizeof(val)...`.
Software Monkey
+1  A: 

fread return the number of elements read, not number of bytes.

(Incidentally, in your code you mistakenly give it an element count of 2 which causes a buffer overflow).

You should check fread's return value so you won't run into infinite loops in the case of errors.

Instead of querying for the file size, I would simply call fread (or other input functions) in a loop until the end of file.

Amnon