[CMake entry and advanced (12)] File operations in CMake (with code)

        cmake provides the file() command to perform a series of operations on files, such as reading and writing files, deleting files, renaming files, copying files, creating directories, etc. In this article, we will learn this powerful file() command together.

1. Write files: write and append content

        Use the file() command to write files, as shown below:

file(WRITE <filename> <content>...)
file(APPEND <filename> <content>...)

        will be written to a file named . If the file does not exist, it will be created; if the file already exists, WRITE mode will overwrite it, and APPEND mode will append the content to the end of the file.

        The test code is as follows:

# file()写文件测试
file(WRITE wtest.txt "Hello World!") #给定内容生成 wtest.txt 文件
file(APPEND wtest.txt " China") #给定内容追加到 wtest.txt 文件末尾

        Note that files can be specified using absolute or relative paths, relative paths are interpreted relative to the current source path.

        After executing the CMakeLists.txt code, a file named wtest.txt will be generated in the current source code directory, as follows:

         Then check the contents of the wtest.txt file, as follows:

 2. Write files: generate files from content

        The command to generate a file from content is:

file(GENERATE OUTPUT output-file
    <INPUT input-file|CONTENT content>
    [CONDITION expression])

        output-file: Specify the output file name, which can have a path (absolute path or relative path);

        INPUT input-file: Specify the input file, and generate the output file through the content of the input file;

        CONTENT content: Specify the content, directly specify the content to generate the output file;

        CONDITION expression: If the condition of the expression expression is judged to be true, the file will be generated, otherwise it will not be generated.

        Similarly, the specified file can use either a relative path or an absolute path, but here, the relative path is interpreted as the BINARY_DIR path relative to the current source code, not the current source code path.

        The test code is as follows:

# 由前面生成的 wtest.txt 中的内容去生成 out1.txt 文件
file(GENERATE OUTPUT out1.txt INPUT "${PROJECT_SOURCE_DIR}/wtest.txt")

# 由指定的内容生成 out2.txt
file(GENERATE OUTPUT out2.txt CONTENT "This is the out2.txt file")

# 由指定的内容生成 out3.txt,加上条件控制,用户可根据实际情况
# 用表达式判断是否需要生成文件,这里只是演示,直接是 1
file(GENERATE OUTPUT out3.txt CONTENT "This is the out3.txt file" CONDITION 1)

        Go to the build directory and execute cmake:

         After executing cmake, three files out1.txt, out2.txt and out3.txt will be generated under the build directory (that is, the BINARY_DIR of the top-level source code), the contents are as follows:

3. Read file: byte read 

        The file() read file command format is as follows:

file(READ <filename> <variable>
    [OFFSET <offset>] [LIMIT <max-in>] [HEX])

        Read content from the file named and store it in <variable>.

        Optionally start at the given <offset> and read at most <max-in> bytes. The HEX option causes the data to be converted to a hexadecimal representation (useful for binary data).

        Similarly, the specified file can use either a relative path or an absolute path, and the relative path is interpreted as relative to the current source code path. The test code is as follows:

# file()读文件测试
file(READ "${PROJECT_SOURCE_DIR}/wtest.txt" out_var) #读取前面生成的 wtest.txt
message(${out_var}) # 打印输出

# 读取 wtest.txt 文件:限定起始字节和大小
file(READ "${PROJECT_SOURCE_DIR}/wtest.txt" out_var OFFSET 0 LIMIT 10)
message(${out_var})

# 读取 wtest.txt 文件:以二进制形式读取,限定起始字节和大小,
file(READ "${PROJECT_SOURCE_DIR}/wtest.txt" out_var OFFSET 0 LIMIT 5 HEX)
message(${out_var})

        The print information is as follows:

 4. Read as a string

        The command format is as follows:

file(STRINGS <filename> <variable> [<options>...])

        file(STRINGS [...]) Parses a list of ASCII strings from a file and stores them in. This command is dedicated to reading strings, and the binary data in the file will be ignored, and carriage return (\r, CR) characters will be ignored.

        filename: Specify the file to be read. You can use an absolute path or a relative path. The relative path is interpreted as relative to the current source code path.

        variable: A variable that stores strings.

        options: Optional parameters, you can choose 0, 1 or more options, these options include:

➢ LENGTH_MAXIMUM: the maximum length of the string to be read;

➢ LENGTH_MINIMUM: the minimum length of the string to be read;

➢ LIMIT_COUNT: the number of lines to read;

➢ LIMIT_INPUT: the number of bytes read;

➢ LIMIT_OUTPUT: limit the number of bytes stored in variables;

➢ NEWLINE_CONSUME: take line breaks into account;

➢ NO_HEX_CONVERSION: Unless this option is provided, Intel Hex and Motorola S-record files are automatically converted to binary files when read.

➢ REGEX: Only read the lines that meet the regular expression;

➢ ENCODING: specify the encoding format of the input file, currently supported encodings are: UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE. If the ENCODING option is not provided and the file has a Byte Order Mark, the ENCODING option will default to respect the Byte Order Mark.

        The test code is as follows:

# 从 input.txt 文件读取字符串
file(STRINGS "${PROJECT_SOURCE_DIR}/input.txt" out_var)
message("${out_var}")

# 限定读取字符串的最大长度
file(STRINGS "${PROJECT_SOURCE_DIR}/input.txt" out_var LENGTH_MAXIMUM 5)
message("${out_var}")

# 限定读取字符串的最小长度
file(STRINGS "${PROJECT_SOURCE_DIR}/input.txt" out_var LENGTH_MINIMUM 4)
message("${out_var}")

# 限定读取行数
file(STRINGS "${PROJECT_SOURCE_DIR}/input.txt" out_var LIMIT_COUNT 3)
message("${out_var}")

        Read the string from the input.txt file, the content of the input.txt file is as follows:

         The result of executing the above code is as follows:

 5. Calculate the hash value of the file

        The file() command can calculate a cryptographic hash (hash value) of the specified file content and store it in a variable. As follows:

file(<MD5|SHA1|SHA224|SHA256|SHA384|SHA512> <filename> <variable>)

        MD5|SHA1|SHA224|SHA256|SHA384|SHA512 represent different hash calculation algorithms, one of which must be specified, filename specifies the file (absolute path or relative path can be used, and the relative path is interpreted as relative to the current source code BINARY_DIR), store the calculation result in the variable variable.

        The test code is as follows:

# 计算文件的 hash 值
file(SHA256 "${PROJECT_SOURCE_DIR}/input.txt" out_var)
message("${out_var}")

        Here we still use the input.txt file created above and use the SHA256 algorithm for calculation, the results are as follows:

6. File renaming

        Use the file() command to rename a file. The format of the command is as follows:

file(RENAME <oldname> <newname>)

        oldname refers to the original file, and newname refers to the new file after renaming. The file can be specified using either an absolute path or a relative path. The relative path is interpreted as relative to the current source code path.

        Test code:

# 文件重命名
file(RENAME "${PROJECT_SOURCE_DIR}/input.txt" "${PROJECT_SOURCE_DIR}/output.txt")

        The test results are as follows:

 7. Delete files

        Use the file() command to delete files. The command format is as follows:

file(REMOVE [<files>...])
file(REMOVE_RECURSE [<files>...])

        The REMOVE option will delete the given file, but not the directory; while the REMOVE_RECURSE option will delete the given file or directory, and a non-empty directory. The specified file or directory can use either an absolute path or a relative path, and the relative path is interpreted as relative to the current source path. Test code:

# file 删除文件或目录测试
file(REMOVE "${PROJECT_SOURCE_DIR}/out1.txt")
file(REMOVE_RECURSE "${PROJECT_SOURCE_DIR}/out2.txt" "${PROJECT_SOURCE_DIR}/empty-dir"
"${PROJECT_SOURCE_DIR}/Non_empty-dir")

        out1.txt and out2.txt are ordinary files, empty-dir is an empty directory, and Non_empty-dir is a non-empty directory, as follows:

         Go to the build directory and execute cmake:

         After executing the cmake command, these files and folders are deleted.

        I have introduced so much about the file() command. In fact, the file() command is very powerful. In addition to the basic functions introduced above, it also supports file download, file lock and other functions.

Guess you like

Origin blog.csdn.net/cj_lsk/article/details/131328010