C gets an example of a file size

  • 2020-04-02 02:12:38
  • OfStack

1. The fseek

Function prototype:


int fseek ( FILE * stream, long int offset, int origin );

Parameter description: stream, file stream pointer; Offest, offset; Orgin, original position. The optional values for orgin are SEEK_SET(the beginning of the file), SEEK_CUR(the current position of the file pointer), and SEEK_END(the end of the file).

Function description: for binary mode open flow, the new position is origin + offset.

2. The ftell

Function prototype: long int ftell (FILE * stream);

Returns the position of the stream. The return value for the binary stream is the number of bytes from the start of the file.

Get file size C program (file.cpp) :


#include <stdio.h>
int main ()
{
      FILE * pFile;
      long size;
      pFile = fopen ("file.cpp","rb");
      if (pFile==NULL)
            perror ("Error opening file");
      else
      {
            fseek (pFile, 0, SEEK_END);   /// moves the file pointer to the end of the file
            size=ftell (pFile); //Finds the number of bytes from the current file pointer to the start of the file
            fclose (pFile);
            printf ("Size of file.cpp: %ld bytes.n",size);
      }
      return 0;
}


Related articles: