Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions nob.c
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const char *test_names[] = {
"cmd_redirect",
"cmd_args_passing",
"read_entire_dir",
"copy_alias",
"da_resize",
"da_last",
"da_remove_unordered",
Expand Down
17 changes: 16 additions & 1 deletion nob.h
Original file line number Diff line number Diff line change
Expand Up @@ -1238,12 +1238,27 @@ NOBDEF bool nob_copy_file(const char *src_path, const char *dst_path)
nob_return_defer(false);
}

dst_fd = open(dst_path, O_CREAT | O_TRUNC | O_WRONLY, src_stat.st_mode);
dst_fd = open(dst_path, O_CREAT | O_WRONLY, src_stat.st_mode);
if (dst_fd < 0) {
nob_log(NOB_ERROR, "Could not create file %s: %s", dst_path, strerror(errno));
nob_return_defer(false);
}

// Distinct paths (including hard links) may name the same file.
struct stat dst_stat;
if (fstat(dst_fd, &dst_stat) < 0) {
nob_log(NOB_ERROR, "Could not stat destination %s: %s", dst_path, strerror(errno));
nob_return_defer(false);
}
if (src_stat.st_dev == dst_stat.st_dev && src_stat.st_ino == dst_stat.st_ino) {
nob_log(NOB_ERROR, "%s and %s are the same file", src_path, dst_path);
nob_return_defer(false);
}
if (S_ISREG(dst_stat.st_mode) && ftruncate(dst_fd, 0) < 0) {
nob_log(NOB_ERROR, "Could not truncate %s: %s", dst_path, strerror(errno));
nob_return_defer(false);
}

for (;;) {
ssize_t n = read(src_fd, buf, buf_size);
if (n == 0) break;
Expand Down
19 changes: 19 additions & 0 deletions tests/copy_alias.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#include "shared.h"

int main(void)
{
const char bytes[] = {'a', '\0', 'b'};
if (!write_entire_file("source", bytes, sizeof(bytes))) return 1;
#ifndef _WIN32
const char *alias = link("source", "alias") == 0 ? "alias" : "./source";
if (copy_file("source", alias)) return 1;
#endif
if (!write_entire_file("dest", "longer", 6)) return 1;
if (!copy_file("source", "dest")) return 1;
String_Builder sb = {0};
if (!read_entire_file("dest", &sb)) return 1;
if (sb.count != sizeof(bytes) || memcmp(sb.items, bytes, sb.count) != 0) return 1;
printf("Copied %zu bytes\n", sb.count);
sb_free(sb);
return 0;
}
1 change: 1 addition & 0 deletions tests/copy_alias.stdout.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Copied 3 bytes
1 change: 1 addition & 0 deletions tests/copy_alias.win32.stdout.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Copied 3 bytes