0

i tried to write a function that sample 4 bytes from card.raw file but i doesn't work because fread doesn't put any data into block buffer so i wrote this simple code and i found out that fgetc works while fread doesn't

FILE *ptr = fopen("card.raw","w+"); unsigned char *block = malloc(sizeof(unsigned char) * 512); if (block == NULL) { fprintf(stderr, "couldn't allocate memory\n"); return 5; } fread(block, 1, 512, ptr); unsigned char c = fgetc(ptr); printf("*block = %i\nc = %i\n", *block ,c); 

that's the output of this program

*block = 0 c = 255 

and the same thing happens when i try to use array instead of using malloc any idea why is this happening ?

1
  • fread returns 0 Commented Jun 11, 2019 at 16:37

1 Answer 1

2

You just opened your file for writing (and reading). This erased your card.raw's content.

The 0 you find in block[0] is the initial value of your allocated memory, which by coincidence is 0.

The 255 you find in c is actually a -1 returned by fgetc (and means EOF - End Of File). When converting the int-type -1 to an unsigned char, only the least significant byte is kept, which in this case corresponds to value 255.

Use r, not w+ for reading (and replace card.raw with a working copy).

Also, in this problem, there is little use for fgetc. You are meant to always read 512 bytes at a time.

4
  • i almost forgot about "w" erasing all file's contents , one last thing , when i edited the code fread worked fine but i always get 0 when i try to print any element of "block" pointer , unlike fgetc i get number 99 - and if used it again i get 115 - unlike block[0] and block[1] Commented Jun 11, 2019 at 17:26
  • ok i tried other block and "block" elements have values now but i still can't understand why fgetc has get values in first block although it's all zeros, i'm sorry for my dumb question Commented Jun 11, 2019 at 18:08
  • Sorry, I can't follow you. I don't know how you changed your code, I don't know which values you refer to. Maybe make a new question, since it's another problem. Also, both fread and fgetc move the position within the file. Commented Jun 11, 2019 at 18:43
  • ok i will do that and thank you for your help really appreciate it Commented Jun 11, 2019 at 18:51

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.