当前位置:网站首页>C language to get file size

C language to get file size

2020-12-07 10:28:09 osc_ k4am9e6e

C Language is a lower level language , Things that are sometimes easy to manipulate in other languages , stay C The language is more troublesome , For example, get the size of a file . Many languages can call functions directly to solve ,C There is no corresponding function to get the file size , Here's a simple way .

The code is as follows :

int main()
{
char filename[100];
FILE *fp=fopen(filename,“r”);//filename For the file name to open ,r To open the file format
// Open file in new version fopen_s(&fp,filename,“r”);
if(!fp) return -1;
fseek(fp,0L,SEEK_END);//fseek Is a library function ,SEEK_END Go to the end of the file
int size=ftell(fp);//ftell Is a library function
fclose(fp);// File close
printf(“ File size is %d Bytes ”,size);
return 0;
}










This way is through fseek Move the file pointer to the end , Re pass ftell Function to read the file size , because ftell The return value of is long, So the number of bytes cannot exceed long The value of , In general, the file cannot exceed 2G size , Otherwise it will go wrong .

If the file is large , Can pass fsetpos and fgetpos Get file size . The most fatal flaw is that it needs to load files into memory , Then jump to the end of the file , This operation is very time consuming !

版权声明
本文为[osc_ k4am9e6e]所创,转载请带上原文链接,感谢
https://chowdera.com/2020/12/202012071026183873.html