0

How does fread actually work? In pset4 recover, i did this

 while (fread(buffer,sizeof(BYTE)*512, 1, inptr) == 1)
{
    //If signature of first 4 elements is jpeg, create new file and write that block
    if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
    {
        sprintf(filename, "%03i.jpg", i);
        i++;
        outptr = fopen(filename, "w");
        if (outptr == NULL)
        {
            printf("Cannot create file\n");
            return 3;
        }
        fwrite(buffer, sizeof(BYTE)*512, 1, outptr);
    }
    //Write blocks following a jpeg signature block in the same file as that jpeg signature block
    if (!(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0))
    {
        if (i>0)
        {
            fwrite(buffer, sizeof(BYTE)*512, 1, outptr);
        }

    }    

I have finished the assignment but i still cant wrap my head around how fread actually works. In this case, my buffer is 512bytes and the file which i am reading from is way bigger. So my understanding is that the file pointer cursor for reading does not repeat itself by going back to the start of the file and once it stores information in buffer, the file pointer cursor halts until something happens. Can someone fully explain how fread works with relation to the file pointer cursor? Much help appreciated! :)

0

fread works as you describe. The cursor moves and stays in this position until you call fread again. Until EOF. Seems in your code you miss closing files. It should look (except the first file which is a bit different):

  1. if the first four bytes look like jpg:
  2. close previous file
  3. open new one
  4. keep read-write until first four bytes look like jpg. Go to 2.
  5. repeat until EOF
| improve this answer | |
  • why do i need to close files? In my code,i reassigned a new file to the pointer outptr so that should have closed the previous file already right? And u say cursor stays in position until i call fread again, so in this case my while loop keeps calling fread right? Just curious, is there a way to allow file cursor to go to the beginning without using fseek? – Shane Aug 1 '17 at 16:34
  • 1. You need to "manually" close files to free allocated memory. In the next Week, there will be more about it. 2. Yes, in this case the loop keeps calling fread. 3. Check rewind() function. – obesman Aug 1 '17 at 17:04

You must log in to answer this question.

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