Operations related to getting file size in C Language
Operations related to getting file size in C Language
Description
Generally, you want to assign all the data from the file to an array or a pointer, and then perform related data processing, such as decoding. Before assigning values, the array or pointer must be allocated with memory. Generally, the array can be directly allocated with the maximum number of bytes of the file, or the pointer can be allocated with malloc based on the maximum number of bytes, however, this will cause a waste of memory, which cannot be tolerated by programmers pursuing perfection. Therefore, a very suitable method is to obtain the file size in advance before reading the specific data of the file, and then use malloc to allocate memory for the pointer, and then read the data, directly fread the corresponding data. This article provides a simple method to get the file size.
Program code
FILE * fImage; int Length; unsigned char * ImageData; if (fImage = fopen (Bretagne2.j2k, rb ))! = NULL) // find the file size! {Fseek (fImage, 0, SEEK_END); Length = ftell (fImage); printf (data size = % ld, Length); fseek (fImage, 0, SEEK_SET ); imageData = (unsigned char *) malloc (Length); fread (ImageData, 1, Length, fImage); if (! ImageData) {printf (malloc error! ); Return;} fclose (fImage);} else {printf (Open Data error !); Return ;}
First, open the file, adjust the file pointer to the end of the file, and then use ftell to obtain the position of the file pointer, the ftell return value is used to obtain the number of offset bytes from the current position of the file position pointer to the first part of the file. In this way, we can easily get the size of this file. At the same time, it is very convenient to directly use malloc for memory allocation and then directly read it.