Louis Better than before

Some of Common C library functions

fread, fseek and ftell functions

fread function

This function is used for reading data from the given file pointer into the array pointer.

Usage:

size_t fread(void *arr_ptr, size_t size, size_t element, FILE *file)

fseek function

This function is used for setting the position of the file pointer to the given offset.

Usage:

int fseek(FILE *file, long int offset, int position)

The position is specified by the following constants:

  1. SEEK_END: End of file
  2. SEEK_SET: Starting of file
  3. SEEK_CUR: Current position of file pointer

ftell function

This function is used for returnning the current position of the given file pointer.

Usage:

long int ftell(FILE *file)

Example:

int main(int argc, char **argv) {
  FILE *fp_in = NULL;
  char data[100];
  long int position;

  char *filename = "data.txt";

  fp_in = fopen(filename, "rb");

  // Read data chunk
  fread(data, 1, 100, fp_in);

  // Read the position of pointer
  position = ftell(fp_in);
  printf("the position of pointer = %d \n", position);

  fseek(fp_in, 10, SEEK_CUR);    // shift 10 bytes

  // Read the position of pointer
  position = ftell(fp_in);
  printf("the position of pointer after shifting= %d \n", position);

  return 0;
}

Result:

the position of pointer = 100 
the position of pointer after shifting= 110

=========== To be continued…. ==========

Reference

[1] C library function - fseek

[2] C library function - fread

[3] C library function - ftell

Note

If you have any constructive criticism or advises, leave the comments below or feel free to email me @qazqazqaz850@gmail.com. Hope this post will help! :)