0

I just have a conceptual question for how fread and fseek works in the context of the pset4's recover assignment. Initially when I was trying to write my program for this assignment, I was using fseek to iterate through the next 512 block of Bytes after every iteration of the while loop. I was using the following code

FILE *memory_file = fopen(argv[1], "r");            
int i = 0;
fseek(memory_file, (512 * i), SEEK_SET);
i++;                                                                                                                                     
fread(BYTES, 1, 512, memory_file);

However, for some reason this wasn't working. Would using fseek in this contxt be wrong?

Then I changed the code by removing the fseek call and I started simply reading 512 Bytes from the memory_file and writing it into a new file that I have opened up and the assignment worked and got full marks.

Based on the above, it appears as though fread reads the next 512 bytes from where it is currently located in the file and not always from the start of the file. So for example in the 2nd iteration of the while loop, fread will read 512 bytes from the memory_file starting from Bytes #513 to Bytes #1024. Can you confirm if this is indeed how fread behaves?

Thank you.

1 Answer 1

1

Indeed!, the pointer, memory_file in this case, is initially located at the beginning of the file, when the file is opened, and it advances sequentially as data is read. However, this file pointer can be placed in any position, using the fseek () function and the ftell () function allows obtaining the current position of the file pointer.

4
  • Hi. Thank you for your comment. Follow up question: So fread is going to sequentially read through the 512 Bytes sized block one at a time. Technically speaking using fseek should result in the same behavior (if I iterate through each block sized 512 Bytes) right? Commented Apr 16, 2020 at 16:20
  • By the same behavior I suppose you mean that the pointer goes back one block, that is, we would read the same 512-byte block again in a new fread () pass
    – MARS
    Commented Apr 16, 2020 at 16:28
  • Sorry what I mean by same behavior was that for example in the code above, when i = 1, will fread store into BYTES 512 Bytes starting from Byte #513 to Byte #1024? or would it store into BYTES from Byte # 0 to # 512? Commented Apr 16, 2020 at 16:35
  • Regarding your particular code, we place the course in byte 512 from the beginning of the file, not in 512 +1.
    – MARS
    Commented Apr 16, 2020 at 17:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .