1 //===- Support/FileUtilities.cpp - File System Utilities ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a family of utility functions which are useful for doing
11 // various things with files.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Support/FileUtilities.h"
16 #include "llvm/System/Path.h"
22 /// DiffFiles - Compare the two files specified, returning true if they are
23 /// different or if there is a file error. If you specify a string to fill in
24 /// for the error option, it will set the string to an error message if an error
25 /// occurs, allowing the caller to distinguish between a failed diff and a file
28 bool llvm::DiffFiles(const std::string &FileA, const std::string &FileB,
30 std::ios::openmode io_mode = std::ios::in | std::ios::binary;
31 std::ifstream FileAStream(FileA.c_str(), io_mode);
33 if (Error) *Error = "Couldn't open file '" + FileA + "'";
37 std::ifstream FileBStream(FileB.c_str(), io_mode);
39 if (Error) *Error = "Couldn't open file '" + FileB + "'";
43 // Compare the two files...
46 C1 = FileAStream.get();
47 C2 = FileBStream.get();
48 if (C1 != C2) return true;
54 /// MoveFileOverIfUpdated - If the file specified by New is different than Old,
55 /// or if Old does not exist, move the New file over the Old file. Otherwise,
56 /// remove the New file.
58 void llvm::MoveFileOverIfUpdated(const std::string &New,
59 const std::string &Old) {
60 if (DiffFiles(New, Old)) {
61 if (std::rename(New.c_str(), Old.c_str()))
62 std::cerr << "Error renaming '" << New << "' to '" << Old << "'!\n";
64 std::remove(New.c_str());