Filesystem Interaction, Pathname Manipulation

file: Host Filesystem Access

  • Set of methods to interact with the host filesystem

  • Complemented by cmake_path(): path manipulation, without any filesystem interaction

file(READ ...): Read Entire File

  • Reads an entire file into a variable

  • ⟶ optional size limit

file(READ "/etc/passwd" passwd_content)
message("${passwd_content}")
$ cmake -P file-read.cmake
root:x:0:0:Super User:/root:/bin/bash
bin:x:1:1:bin:/bin:/usr/sbin/nologin
daemon:x:2:2:daemon:/sbin:/usr/sbin/nologin
adm:x:3:4:adm:/var/adm:/usr/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/usr/sbin/nologin
...

file(STRINGS ...): Read Lines Of File

  • Reads file as list of lines

  • Can do filtering based on regular expressions

  • … encoding …

file(STRINGS "/etc/passwd" passwd_lines)
foreach(line ${passwd_lines})
  message("${line}")
endforeach()
$ cmake -P file-read-lines-of-file.cmake
root:x:0:0:Super User:/root:/bin/bash
bin:x:1:1:bin:/bin:/usr/sbin/nologin
daemon:x:2:2:daemon:/sbin:/usr/sbin/nologin
adm:x:3:4:adm:/var/adm:/usr/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/usr/sbin/nologin
...

file(<HASH> ...): Checksumming

file(SHA256 "/etc/passwd" passwd_hash)
message("${passwd_hash}")
$ cmake -P file-hash.cmake
2cf0baaebfbfbdbaaf1ded5385d50b6c0fb883f7ffc60a33da9381b84bba5407

file(WRITE ...), file(APPEND ...): Writing Files

file(APPEND "/tmp/nonsense" "one-line\n")
$ cmake -P file-append.cmake

file(GLOB ...): Read Directory Contents

For example, read all *.cpp files from current working directory

file(GLOB cpp_files "*.cpp")
foreach(cpp_file ${cpp_files})
  message("${cpp_file}")
endforeach()
$ cmake -P file-glob-cpp.cmake
/home/jfasch/My-Projects/jfasch-home/trainings/material/soup/cmake/advanced/language/file-etc/code/file1.cpp
/home/jfasch/My-Projects/jfasch-home/trainings/material/soup/cmake/advanced/language/file-etc/code/file2.cpp

cmake_path(GET ...): Decompose Paths

  • ROOT_NAME, ROOT_DIRECTORY, ROOT_PATH, FILENAME, EXTENSION, STEM, RELATIVE_PART, PARENT_PATH

  • For example, how to get the filename component (FILENAME) of an absolute path

set(full_path "/home/jfasch/My-Projects/jfasch-home/trainings/material/soup/cmake/advanced/language/file-etc/code/file1.cpp")
cmake_path(GET full_path FILENAME filename_part)
message("${filename_part}")
$ cmake -P cmake-path-get-filename.cmake
file1.cpp

cmake_path(APPEND ...): Compose Paths

For example, add one path component to existing path

set(some_path "/path/to/parent")
cmake_path(APPEND some_path "child")
message("${some_path}")
$ cmake -P cmake-path-append.cmake
/path/to/parent/child