readfile

Table of Contents

Prototype: readfile(filename, maxbytes)

Return type: string

Description: Returns the first maxbytes bytes from file filename. When maxbytes is 0, the maximum possible bytes will be read from the file (but see Notes below).

Arguments:

  • filename: string, in the range: "?(/.*)
  • maxbytes: int, in the range: 0,99999999999

Example:

Prepare:

echo alpha > /tmp/cfe_hostlist
echo beta >> /tmp/cfe_hostlist
echo gamma >> /tmp/cfe_hostlist

Run:

body common control
{
      bundlesequence => { "example" };
}

bundle agent example
{
  vars:

      "xxx"
      string => readfile( "/tmp/cfe_hostlist" , "5" );
  reports:
      "first 5 characters of /tmp/cfe_hostlist: $(xxx)";
}

Output:

R: first 5 characters of /tmp/cfe_hostlist: alpha

Notes:

  • To reliably read files located within /proc or /sys directories, maxsize has to be set to 0.

  • At the moment, only 4095 bytes can fit into a string variable. This limitation may be removed in the future. If this should happen, a warning will be printed.

  • If you request more bytes than CFEngine can read into a string variable (e.g. 999999999), a warning will also be printed.

  • If either because you specified a large value, or you specified 0, more bytes are read than will fit in a string, the string is truncated to the maximum.

  • On Windows, the file will be read in text mode, which means that CRLF line endings will be converted to LF line endings in the resulting variable. This can make the variable length shorter than the size of the file being read.

History: Warnings about the size limit and the special 0 value were introduced in 3.6.0