C language Get file size related operations
Disclaimer: Reference Please specify source http://blog.csdn.net/lg1259156776/
Description
Usually in the hope that the data from the file will be assigned to an array or a pointer, and then the related data processing, such as decoding operations. Before the assignment, the array or pointer needs to allocate memory, usually for the array can be directly in the file maximum number of bytes allocated, or the pointer with malloc also by the maximum byte allocation, but this will cause memory waste, for the pursuit of perfect programmer is not tolerated. So a very suitable method is to read the file specific data before the file size can be obtained in advance, and then use malloc to allocate the pointer memory, and then the data read, directly fread the corresponding data. This paper gives a simple method to get the file size.
Program code
FILE * fImage; int Length; unsigned char * ImageData; if((fImage=fopen("Bretagne2.j2k","rb"))!=NULL)//寻找文件的大小! { fseek(fImage,0,SEEK_END); Length=ftell(fImage); printf("data size = %ld\n",Length); fseek(fImage,0,SEEK_SET); ImageData = (unsigned char *)malloc(Length); fread(ImageData,1,Length,fImage); if(!ImageData) { printf("malloc error! \n"); return; } fclose(fImage); } else { printf("Open Data error!\n"); return; }
The first is to open the file, then adjust the file pointer to the end of the file, and then use Ftell to get the position of the file pointer, Ftell the return value is used to get the file location pointer the current position relative to the head of the file offset bytes. This makes it easy to get the size of the file. At the same time, directly using malloc for memory allocation, and then directly read, it is very convenient.
2015-10-18 Debug Record Summary Zhang Bongyi
Copyright NOTICE: This article for Bo Master original article, reprint please indicate source http://blog.csdn.net/lg1259156776/.
C language Get file size related operations