cmacosfile-copying

c: using copyfile.h for Mac


I am playing with the Mac OSX copyfile function to move a file using C. Header file found here

int copyfile(const char *from, const char *to, copyfile_state_t state, copyfile_flags_t flags);

Here is my code:

#include <copyfile.h>

    int main() {
    int success;
    const char* from = "hello.text";
    const char* to = "/toGo/hello.txt";
    copyfile_state_t state = copyfile_init();
    copyfile_flags_t flags = "COPYFILE_MOVE";

    success = copyfile(from, to, state, flags);
    printf ("%d\n", success);
    exit(0);
}

I added copyfile_init() function to initialize the state. And I get compiling issues now but I think I am getting in the right direction.

$ gcc move.c
Undefined symbols for architecture x86_64:
  "_copyfile_init", referenced from:
  _main in ccXJr5oN.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status

Based on what I've seen online this is a linking issue. So I added the link tag but it's not finding the file, and this header is supposed to be in OSX source.

$ gcc move.c -lcopyfile
ld: library not found for -lcopyfile

Solution

  • COPYFILE_MOVE is a flag constant. It doesn't belong in a string. To actually transfer the file's data, you'll also need to set the COPYFILE_DATA flag.

    Also, you can leave out the state parameter. (You didn't bother to initialize it anyway.) Just pass NULL instead.

    This should work:

    #include <stdio.h>
    #include <copyfile.h>
    
    int main() {
      int success;
      const char* from = "hello.text";
      const char* to = "/toGo/hello.txt";
      copyfile_flags_t flags = COPYFILE_MOVE | COPYFILE_DATA;
      success = copyfile(from, to, NULL, flags);
      printf ("%d\n", success);
      return 0;
    }