samefile is a header-only C89 library for checking whether two paths refer to the same file.
It is designed to stay portable and simple:
- Header-only distribution
- POSIX support through
devandino - Windows support through file identifiers and Win32 error messages
- Explicit error reporting through
SFResult
typedef struct SFResult SFResult;
static SFResult sf_is_same_file(const char *p1, const char *p2);
static void sf_free_result(const SFResult r);sf_is_same_file() returns:
is_err == SF_FALSEwhen the call succeededdata.value.v == SF_TRUEwhen both paths point to the same filedata.value.v == SF_FALSEwhen both paths point to different filesis_err == SF_TRUEwhen an error occurred
When is_err == SF_TRUE, data.err points to a heap-allocated message. Call sf_free_result() after handling the error.
#include <stdio.h>
#include "samefile.h"
int main(void) {
SFResult r = sf_is_same_file("a.txt", "b.txt");
if (r.is_err) {
fprintf(stderr, "%s\n", r.data.err ? r.data.err : "unknown error");
sf_free_result(r);
return 1;
}
if (r.data.value.v == SF_TRUE) {
puts("same file");
} else {
puts("different files");
}
return 0;
}Add the project as a subdirectory:
add_subdirectory(path/to/samefile)
target_link_libraries(your_target PRIVATE samefile)The library is header-only, so linking only forwards the include directory.
cmake -S . -B build
cmake --build build
cmake --install build --prefix /your/prefixThis installs:
include/samefile.hlib/cmake/samefile/samefileTargets.cmake
- On POSIX platforms, file identity is checked with
fstat(). - On Windows, the library first tries
GetFileInformationByHandleEx()withFileIdInfo. IfFileIdInfois unavailable, it falls back toGetFileInformationByHandle(). - Windows failures are converted into readable messages with
FormatMessageA().
MIT