Skip to content

reading file example

marpaia edited this page Oct 7, 2014 · 9 revisions

include/osquery/filesystem.h contains various utilities for accessing the filesystem.

Consider the following example for reading a file from the filesystem (without error checking):

#include <iostream>
#include <string>
#include "osquery/filesystem.h"

int main(int argc, char* argv[]) {
  std::string content;
  osquery::readFile("/foo/bar.txt", content);
  std::cout << "Contents of " << kPath << ":\n" << content;
  return 0;
}

Consider the same example, with error checking:

#include <iostream>
#include <string>
#include "osquery/filesystem.h"

const std::string kPath = "/foo/bar.txt"

int main(int argc, char* argv[]) {
  auto s = osquery::pathExists(kPath);
  if (s.ok()) {
    std::string content;
    s = osquery::readFile(kPath, content);
    if (s.ok()) {
      std::cout << "Contents of " << kPath << ":\n";
      std::cout << content;
    } else {
      std::cerr << "Error reading file: " << s.toString();
      return s.code();
    }
  } else {
    std::cerr << "Error checking if the path exists: " << s.toString();
    return s.code();
  }
  return 0;
}

Clone this wiki locally