base: add API to remove file if it exists.

It is a function needed in different places like uncrypt, simpleperf.

Bug: 26883096
Change-Id: I26f4f30e8367867a88272625f00858569fc8e950
diff --git a/base/file.cpp b/base/file.cpp
index f444c0c..bcdfc5e 100644
--- a/base/file.cpp
+++ b/base/file.cpp
@@ -149,5 +149,32 @@
   return true;
 }
 
+bool RemoveFileIfExists(const std::string& path, std::string* err) {
+  struct stat st;
+#if defined(_WIN32)
+  //TODO: Windows version can't handle symbol link correctly.
+  int result = stat(path.c_str(), &st);
+  bool file_type_removable = (result == 0 && S_ISREG(st.st_mode));
+#else
+  int result = lstat(path.c_str(), &st);
+  bool file_type_removable = (result == 0 && (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)));
+#endif
+  if (result == 0) {
+    if (!file_type_removable) {
+      if (err != nullptr) {
+        *err = "is not a regular or symbol link file";
+      }
+      return false;
+    }
+    if (unlink(path.c_str()) == -1) {
+      if (err != nullptr) {
+        *err = strerror(errno);
+      }
+      return false;
+    }
+  }
+  return true;
+}
+
 }  // namespace base
 }  // namespace android