• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2022 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "util/atomic_write.h"
6 
7 #include "base/files/file_util.h"
8 
9 namespace util {
10 
WriteFileAtomically(const base::FilePath & filename,const char * data,int size)11 int WriteFileAtomically(const base::FilePath& filename,
12                         const char* data,
13                         int size) {
14   base::FilePath dir = filename.DirName();
15   base::FilePath temp_file_path;
16 
17   {
18     base::File temp_file =
19         base::CreateAndOpenTemporaryFileInDir(dir, &temp_file_path);
20     if (!temp_file.IsValid()) {
21       return -1;
22     }
23     if (temp_file.WriteAtCurrentPos(data, size) != size) {
24       return -1;
25     }
26   }
27 
28   if (!base::ReplaceFile(temp_file_path, filename, NULL)) {
29     return -1;
30   }
31   return size;
32 }
33 
34 }  // namespace util
35