open (), lseek () at the end of the file, getting the file size using the tell () command, and then allocating memory accordingly will work as suggested above.
If there is no particular reason for this, fopen (), fseek (), ftell () is a better idea (portable within the standard C library).
This, of course, assumes that the file you are opening is small. If you work with large files, allocating memory for the entire file might not be a good idea.
You may like to use memory mapped files for large files. POSIX systems provide the mmap () and munmap () functions for matching files or devices in memory. See mmap man for more details. Files with memory mapping work similarly to C arrays, although the responsibility for obtaining the actual file data is provided by the OS, which extracts the corresponding pages from the disk as necessary when working on the file.
The memory card mapping approach has limitations if the file size is larger than the 32-bit address space. Then you can display only part of the file at a time (on 32-bit machines).
source share