bool WriteStringToFile(const std::string& content, const std::string& path, mode_t mode, uid_t owner, gid_t group) { int fd = TEMP_FAILURE_RETRY( open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW, mode)); if (fd == -1) { fprintf(stderr, "android::WriteStringToFile open failed: %s", strerror(errno)); return false; } // We do an explicit fchmod here because we assume that the caller really // meant what they said and doesn't want the umask-influenced mode. if (fchmod(fd, mode) == -1) { fprintf(stderr, "android::WriteStringToFile fchmod failed: %s", strerror(errno)); return CleanUpAfterFailedWrite(path); } if (fchown(fd, owner, group) == -1) { fprintf(stderr, "android::WriteStringToFile fchown failed: %s", strerror(errno)); return CleanUpAfterFailedWrite(path); } if (!WriteStringToFd(content, fd)) { fprintf(stderr, "android::WriteStringToFile write failed: %s", strerror(errno)); return CleanUpAfterFailedWrite(path); } close(fd); return true; }
bool WriteStringToFile(const std::string &content, const std::string &path, mode_t mode, uid_t owner, gid_t group, bool follow_symlinks) { int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY | (follow_symlinks ? 0 : O_NOFOLLOW); android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode))); if (fd == -1) { PLOG(ERROR) << "android::WriteStringToFile open failed"; return false; } // We do an explicit fchmod here because we assume that the caller really // meant what they said and doesn't want the umask-influenced mode. if (fchmod(fd, mode) == -1) { PLOG(ERROR) << "android::WriteStringToFile fchmod failed"; return CleanUpAfterFailedWrite(path); } if (fchown(fd, owner, group) == -1) { PLOG(ERROR) << "android::WriteStringToFile fchown failed"; return CleanUpAfterFailedWrite(path); } if (!WriteStringToFd(content, fd)) { PLOG(ERROR) << "android::WriteStringToFile write failed"; return CleanUpAfterFailedWrite(path); } return true; }
bool WriteStringToFile(const std::string &content, const std::string &path, bool follow_symlinks) { int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY | (follow_symlinks ? 0 : O_NOFOLLOW); android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), flags, 0666))); if (fd == -1) { return false; } return WriteStringToFd(content, fd) || CleanUpAfterFailedWrite(path); }
bool WriteStringToFile(const std::string& content, const std::string& path) { int fd = TEMP_FAILURE_RETRY( open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW, DEFFILEMODE)); if (fd == -1) { return false; } bool result = WriteStringToFd(content, fd); close(fd); return result || CleanUpAfterFailedWrite(path); }