Skip to content

andrew-ares/samefile

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 

Repository files navigation

samefile

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 dev and ino
  • Windows support through file identifiers and Win32 error messages
  • Explicit error reporting through SFResult

Usage

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_FALSE when the call succeeded
  • data.value.v == SF_TRUE when both paths point to the same file
  • data.value.v == SF_FALSE when both paths point to different files
  • is_err == SF_TRUE when an error occurred

When is_err == SF_TRUE, data.err points to a heap-allocated message. Call sf_free_result() after handling the error.

Example

#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;
}

CMake

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.

Installation

cmake -S . -B build
cmake --build build
cmake --install build --prefix /your/prefix

This installs:

  • include/samefile.h
  • lib/cmake/samefile/samefileTargets.cmake

Platform Notes

  • On POSIX platforms, file identity is checked with fstat().
  • On Windows, the library first tries GetFileInformationByHandleEx() with FileIdInfo. If FileIdInfo is unavailable, it falls back to GetFileInformationByHandle().
  • Windows failures are converted into readable messages with FormatMessageA().

License

MIT

About

Cross platform ANSI C header only library for checking whether two file paths are the same file.

Topics

Resources

License

Stars

Watchers

Forks

Contributors