fread in c code example

Example 1: fread

// from the linux programmer's manual, fread(3)
#include 
#include 

int main()
{
  FILE *fp = fopen("/bin/sh", "rb");
  if (!fp) {
    perror("fopen");
    return EXIT_FAILURE;
  }

  unsigned char buffer[4];

  size_t ret = fread(buffer, 4, 1, fp);
  if (ret != sizeof(*buffer)) {
    fprintf(stderr, "fread() failed: %zu\n", ret);
    exit(EXIT_FAILURE);
  }

  printf("ELF magic: %#04x%02x%02x%02x\n", buffer[0], buffer[1],
         buffer[2], buffer[3]);

  fclose(fp);

  return 0;
}

Example 2: how to use fread to move through a file

Yes, the position of the file pointer is updated automatically after the read operation, so that successive fread() functions read successive file records.

Tags:

Misc Example