Search code examples
windowsscriptingposixcmakeportable-applications

What is the portable way in CMake to determine the size of a file?


I need to determine the number of bytes in an arbitrary file via a CMake script, but in a portable manner.

This file may be large, so reading it in with the file(READ...) command and counting the string length isn't optimal.

If I only had to run on MacOS and/or Linux I'd just use wc -c, which gives me exactly what I want. But the script needs to be Windows compatible assuming only the Windows toolchain. (I'm not very knowledgeable with Windows development.)

I expected this to be a common operation, but am not finding anything similar in the CMake Modules source (likely searching for the wrong thing), and it doesn't appear to be supported by andy of the cmake -E commands.

So I'm looking for either some clever way of getting this info with a single command, or a recommendation on what command(s) I could use in Windows and wrap around a if(WIN32) conditional.


Solution

  • There is a CMake module called FileInformation which lets you obtain the size of a file in a portable way. It adds a new sub-command to CMake's built-in file command:

    file (SIZE filename variable)