Merge "Add option to write to file to graphics detector" into main
diff --git a/common/detector/DetectGraphics.cpp b/common/detector/DetectGraphics.cpp
index d4219a3..bc58dce 100644
--- a/common/detector/DetectGraphics.cpp
+++ b/common/detector/DetectGraphics.cpp
@@ -14,19 +14,45 @@
  * limitations under the License.
  */
 
-#include <string>
-
 #include <google/protobuf/text_format.h>
 
+#include <fstream>
+#include <string>
+
 #include "GraphicsDetector.h"
 #include "GraphicsDetector.pb.h"
 
-int main(int, char*[]) {
+namespace {
+
+bool WriteToFile(const std::string filename, const std::string contents) {
+    std::ofstream ofs(filename);
+    if (!ofs.is_open()) {
+        return false;
+    }
+    ofs << contents;
+    ofs.close();
+    return !ofs.fail();
+}
+
+}  // namespace
+
+int main(int argc, char* argv[]) {
     const auto availability = ::gfxstream::DetectGraphicsAvailability();
 
-    std::string s;
-    if (google::protobuf::TextFormat::PrintToString(availability, &s)) {
-        std::cout << s << std::endl;
+    std::string availabilityString;
+    if (!google::protobuf::TextFormat::PrintToString(availability, &availabilityString)) {
+        std::cerr << "Failed to convert availability to string." << std::endl;
+        return -1;
+    }
+
+    if (argc > 1) {
+        const std::string filename = argv[1];
+        if (!WriteToFile(filename, availabilityString)) {
+            std::cerr << "Failed to write to '" << filename << "'.";
+            return -1;
+        }
+    } else {
+        std::cout << availabilityString << std::endl;
     }
 
     return 0;