#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/xattr.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>

int main(int argc, char *argv[])
{
        int fd;

        if (argc != 2) {
                printf("Use: %s <path>\n", argv[0]);
                return 1;
        }

        /*
         * with O_WRONLY or O_RDWR, opening a directory always fails, even when passing
         * O_DIRECTORY. Opening with O_RDONLY, without O_DIRECTORY succeeds for both
         * regular files and directories.
         */
        fd = open(argv[1], O_WRONLY | O_DIRECTORY); 
        /* fd = open(argv[1], O_RDONLY); */
        if (fd == -1) {
                printf("open error %d: %s\n", errno, strerror(errno));
        } else {
                int e;

                e = fsetxattr(fd, "user.x1", "abc", 3, 0);
                printf("file open fd = %d, setxattr(fd) = %d, fsync(fd) = %d\n", fd, e, fsync(fd));
                close(fd);
        }
        return 0;
}
