Skip to content
This repository was archived by the owner on Feb 5, 2019. It is now read-only.

Commit f21de94

Browse files
committed
Support: Add llvm::sys::fs::copy_file
A function to copy one file's contents to another. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@211302 91177308-0d34-0410-b5e6-96231b3b80d8
1 parent 581d5d5 commit f21de94

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

include/llvm/Support/FileSystem.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -335,6 +335,12 @@ std::error_code remove(const Twine &path, bool IgnoreNonExisting = true);
335335
/// @param to The path to rename to. This is created.
336336
std::error_code rename(const Twine &from, const Twine &to);
337337

338+
/// @brief Copy the contents of \a From to \a To.
339+
///
340+
/// @param From The path to copy from.
341+
/// @param To The path to copy to. This is created.
342+
std::error_code copy_file(const Twine &From, const Twine &To);
343+
338344
/// @brief Resize path to size. File is resized as if by POSIX truncate().
339345
///
340346
/// @param path Input path.

lib/Support/Path.cpp

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -846,6 +846,40 @@ std::error_code create_directories(const Twine &Path, bool IgnoreExisting) {
846846
return create_directory(P, IgnoreExisting);
847847
}
848848

849+
std::error_code copy_file(const Twine &From, const Twine &To) {
850+
int ReadFD, WriteFD;
851+
if (std::error_code EC = openFileForRead(From, ReadFD))
852+
return EC;
853+
if (std::error_code EC = openFileForWrite(To, WriteFD, F_None)) {
854+
close(ReadFD);
855+
return EC;
856+
}
857+
858+
const size_t BufSize = 4096;
859+
char *Buf = new char[BufSize];
860+
int BytesRead = 0, BytesWritten = 0;
861+
for (;;) {
862+
BytesRead = read(ReadFD, Buf, BufSize);
863+
if (BytesRead <= 0)
864+
break;
865+
while (BytesRead) {
866+
BytesWritten = write(WriteFD, Buf, BytesRead);
867+
if (BytesWritten < 0)
868+
break;
869+
BytesRead -= BytesWritten;
870+
}
871+
if (BytesWritten < 0)
872+
break;
873+
}
874+
close(ReadFD);
875+
close(WriteFD);
876+
delete[] Buf;
877+
878+
if (BytesRead < 0 || BytesWritten < 0)
879+
return std::error_code(errno, std::generic_category());
880+
return std::error_code();
881+
}
882+
849883
bool exists(file_status status) {
850884
return status_known(status) && status.type() != file_type::file_not_found;
851885
}

0 commit comments

Comments
 (0)