Get the size of the file for example sharing in C

  • 2020-04-02 02:41:05
  • OfStack

Check the file operation function with C language can be easily implemented. The only functions used in their implementation are fseek and ftell. They are described as follows:

fseek

Grammar:


#include <stdio.h> int fseek( FILE *stream, long offset, int origin );

The function fseek() sets the location data for the given stream. The origin value should be one of the following (defined in stdio.h):

The name of the   instructions
SEEK_SET   Start the search at the beginning of the file
SEEK_CUR   Search from the current location
SEEK_END   Start the search at the end of the file
Fseek () returns 0 on success and non-zero on failure. You can use fseek() to move more than one file, but not before the start. Use fseek() to clear the EOF tag associated with the stream.

ftell

Grammar:


#include <stdio.h> long ftell( FILE *stream );

The code is as follows: the ftell() function returns the current file location of the stream and -1 if an error occurs.


#include <sys/stat.h>  
#include <unistd.h>  
#include <stdio.h>  

int getFileSize(char * strFileName)
{
  FILE * fp = fopen(strFileName, "r");
  fseek(fp, 0L, SEEK_END);
  int size = ftell(fp);
  fclose(fp);
  return size;
}

int getFileSizeSystemCall(char * strFileName)
{
  struct stat temp;
  stat(strFileName, &temp);
  return temp.st_size;
}
int main()
{
  printf("size = %d/n", getFileSize("getFileSize.cpp"));
  printf("size = %d/n", getFileSizeSystemCall("getFileSize.cpp"));
  return 0;
}


Related articles: