In copy.c (and the other apps using the same start code), how does freed know to read one byte after another? It seems to just do it automatically.

Eg, this will read each byte, from first until bi.biWidth, one after the other. How?

    for (int j = 0; j < bi.biWidth; j++)
        RGBTRIPLE triple;
        fread(&triple, sizeof(RGBTRIPLE), 1, inptr);

Is there a way to stop this behaviour and control it manually?

  • Is this stackExchange forum open yet ? You should rather seek for help on the official reddit community (reddit.com/r/cs50). – ItsEric May 13 '14 at 13:27
  • 2
    As of 8 June 2014, this forum is indeed open (cf. edx.org)! – David J. Malan Jun 8 '14 at 16:29
  • @malan Yay ! This will be a huge improvement for the online CS50 community (reddit is great but not for the same reasons SE is). – ItsEric Jun 10 '14 at 9:16

When you open a file a cursor is set somewhere in it (look at man fopen for more about that) and you can change this cursor position using fseek. When you read a "block" (in your case you read sizeof(RGBTRIPLE) bytes) from your file using fread the cursor will be move forward automatically by sizeof(RGBTRIPLE) bytes since your cursor needs to be on each character to read it and to put it in a buffer. You can't read some bytes without moving your cursor (at least not to my knowledge). If you want to go back where you were in your file before reading a triple you use this : fseek(fp, - sizeof(RGBTRIPLE), SEEK_CUR); .

I hope I was clear enough.

Maxow / Eric

  • so in this case [fread(&triple, sizeof(RGBTRIPLE), 1, inptr)] cursor is moved by sizeof(RGBTRIPLE) * 1 ? and if it would be [fread(&triple, sizeof(RGBTRIPLE), 2, inptr)] cursor would move by sizeof(RGBTRIPLE) * 2? I do not get what does exacly do size_t count – koko loko Feb 9 '18 at 5:21

how does freed know to read one byte after another?

It's essentially the definition of fread():

size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );

Reads an array of count elements, each one with a size of size bytes, from the stream and stores them in the block of memory specified by ptr.

In your example

fread(&triple, sizeof(RGBTRIPLE), 1, inptr);

sizeof(RGBTRIPLE) is three bytes, so it will read from the inptr stream, 3 bytes of data, and store it at the location pointed to by &triple.

Because you've got that fread() inside of a loop, it will continue to read/store 3 bytes at a time for as many times as the value of bi.biWidth.

Is there a way to stop this behaviour and control it manually?

If you take it out of a loop, then it will only run once using the arguments you give it.


edited after correction sizeof(RGBTRIPLE) is three bytes, but fread treats it as one element because it is a structure. Jose Manuel. TheBrainyOne.

You must log in to answer this question.

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