Search code examples
cfreadfseek

fseek and fread C programming


EDIT: Thanks everyone for the quick answers. :)

Ok i am new in C and i am able to open a file and set to a certain position in the file and read a chunk of data and write it to another file using this code below:

#include <stdio.h>

int main (int argc, unsigned char *argv[])

  {

      FILE* in = fopen(argv[1], "rb");
      FILE* out = fopen("test.bin", "wb");

      unsigned char buffer[0x200];

      fseek(in, 0x8F00, SEEK_SET);
      fread(buffer, sizeof(buffer), 1, in);   
      fwrite(buffer, sizeof(buffer), 1, out);
  };


But i am kind of versed in perl and i can easily seek to any position in the file and read a chunk of data like this:

seek ( $file, 0x8F00, 0);
read ( $file, $buffer, 0x200);

As you can see i dont have to pre-declare my buffer size in perl, i can specify buffer in the read function itself. Is there anyway at all i can use buffer in C without having to predeclare it like in perl?


Solution

  • No, in C you need to provide a buffer size upfront, and pass that buffer to the fread function.

    You do not need to specify a constant buffer size, though: the size of 0x200 in your case could be calculated at run-time, for example, by examining the size of the file that you are reading.

    Note, however, that when your program selects the size of the buffer dynamically, you should place the buffer in the dynamic memory area, rather than leaving it in the automatic area (i.e. on the stack). This lets you avoid stack overflows when the file is too large, because the restrictions on the automatic memory are usually a lot more severe than the restrictions on the dynamic memory.

    You could also write code that populates the buffer incrementally, expanding it as needed using realloc. See this answer for an example of expanding the read buffer dynamically.