Exorcism Exorcism - 3 months ago 8
C Question

C Binary File Reading Buffer Decleration Location Difference

Hi everyone I am new for C programming and this is my first question, I try to reading binary file in C code, but solution is change when buffer decleration location is changed as commented rows . Why this situation happen?

int main() {
char *ch;
//unsigned char *buffer;
char buffer[129];
//char *buffer;
int counter=0;
FILE *filee;
int x;
int i=0;
filee = fopen("testfile.mtx" , "rb");
int counter2 = 0;

while(1) {
ch = fgetc(filee);
if (ch == EOF)
break;
else
counter ++ ;
}
printf("COUNTER : %d\n",counter);
//buffer = malloc ((sizeof(char) * counter) +1) ;
//unsigned char *buffer = malloc(sizeof(char) * (counter+1));
//char buffer[counter];
fread(buffer,sizeof(buffer),1,filee);
if(filee== NULL) {
printf("Fİle cannot opened\n");
}

for(i = 0; i<counter; i++){
printf("%u ", buffer[i]);
counter2++;
if(counter2 % 8 == 0 ) {
printf("\n");
}
}
fclose(filee);

return 0;
}

Answer

The problem is related to this line:

fread(buffer,sizeof(buffer),1,filee);

Here you use sizeof(buffer) to calculate the number of bytes to read.

When you use

char buffer[129];

you'll get sizeof(buffer) to be 129.

When you use

char *buffer;
buffer = malloc....

you'll get sizeof(buffer) to be the size of a pointer (typically 4 or 8).

Consequently, you read a different number of bytes in the two cases.

You probably want to do:

    fread(buffer, counter, 1, filee);

BTW:

1) You need to go back to the start of the input file before fread

2) The variable dosya is undeclared