file(STRINGS ...) with empty filename does not fail

Recently I was hunting down an issue related to a call to file(STRINGS ...) until I realized that I mispelled a variable name:

file(STRINGS "${mispelledVarName}" content)

As mispelledVarName is not a valid existing variable name this evaluates to:

file(STRINGS "" content)

To my surprise the file function does not fail here, but just returns without any error (leaving the variable content empty).

With a non existing file name like

file(STRINGS "/nonexistent.txt" content)

CMake exits with an error:

CMake Error at test.cmake:x (file):
  file STRINGS file
  "/nonexistent.txt"
  cannot be read.

Shouldn’t an empty filename be handled like a non existing filename? Or is this behavior intended?

It’s probably not intended, but will likely need a policy to turn into an error. Looking at the code, if the path is not absolute, it gets appended to the current source directory. It seems that this ends up reading a directory…but not failing? Does it do the same thing with another directory (not file) path?

All of the following do not fail and return an empty string (tested with CMake 3.22.1):

file(STRINGS "${nonexistent}" content)
message("content: '${content}'")

file(STRINGS "" content)
message("content: '${content}'")

file(STRINGS "/" content)
message("content: '${content}'")

file(STRINGS "." content)
message("content: '${content}'")

Interestingly file(READ ...) behaves a bit different and returns a single newline character instead:

file(READ "" content)
message("content: '${content}'")

file(READ "/" content)
message("content: '${content}'")

file(READ "." content)
message("content: '${content}'")
1 Like

Ugh, thanks. We’ll have to really increase the test suite to cover this policy’s behavior (assuming we want it to fix all relevant file(*) subcommands).

1 Like