Operations related to getting file size in C Language

Source: Internet
Author: User

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.

 

Related Article

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.