Get the size of a file in C language sample sharing _c language

Source: Internet
Author: User

Check it out. It is easy to realize the function of file operation function of the same C language. The functions that are used in the functions that you implement are only Fseek and Ftell. Their descriptions are 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 values (defined in stdio.h):

Name Description
Seek_set start the search from the beginning of the file
Seek_cur start Search from current location
Seek_end start the search at the end of the file
Fseek () returns 0 on success, not 0 on failure. You can use Fseek () to move more than one file, but not before you start. Use Fseek () to clear the EOF tag associated with the stream.

Ftell

Grammar:

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

The code reads as follows: the Ftell () function returns the current file location of the stream (stream), and returns 1 if an error occurs.

#include <sys/stat.h>  
#include <unistd.h>  
#include <stdio.h> 
  /* Function name: getfilesize (char * strFileName) 
  Function: Gets the size parameter of the specified file 
  : 
    strfilename (char *): filename 
  return value: Size 
    (int): File sizes *
/int GetFileSize (char * strFileName)
{
  FILE * fp = fopen (strFileName, "R");
  Fseek (FP, 0L, seek_end);
  int size = Ftell (FP);
  Fclose (FP);
  return size;
}
/* 
  function Name: Getfilesizesystemcall (char * strfilename)  
  feature: Gets the size parameter of the specified file: 
    strFileName (char *): File name 
  return value: Size 
    (int): File 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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.