How to get extended attributes of a file(UNIX/C)?

浪尽此生 提交于 2019-12-01 11:07:46

@ means the file has extended attributes. Use listxattr() to get a list of the names of all the extended attributes, and getxattr() to get the value of a particular attribute. If listxattr returns a non-zero result, you would display @ to indicate this.

Extended attributes are not in POSIX, but this API is available in Linux and OS X, at least.

You can find an example of how to use these functions here.

+ means the file has an access control list. In some filesystems, this is stored as a special extended attribute; in others it's stored separately. For access control lists, see acl(5) for a reference, and you can find an example program that displays it here.

Jenna Maiz

Following is some code I scraped off of the official implementation of ls given by Apple you will find here. The code is long so do CMD + F and search for "printlong".

#include <sys/types.h>
#include <sys/xattr.h>
#include <sys/types.h>
#include <sys/acl.h>
#include <stdio.h>

int main () {
    acl_t acl = NULL;
    acl_entry_t dummy;
    ssize_t xattr = 0;
    char chr;
    char * filename = "/Users/john/desktop/mutations.txt";

    acl = acl_get_link_np(filename, ACL_TYPE_EXTENDED);
    if (acl && acl_get_entry(acl, ACL_FIRST_ENTRY, &dummy) == -1) {
        acl_free(acl);
        acl = NULL;
    }
    xattr = listxattr(filename, NULL, 0, XATTR_NOFOLLOW);
    if (xattr < 0)
        xattr = 0;

    if (xattr > 0)
        chr = '@';
    else if (acl != NULL)
        chr = '+';
    else
        chr = ' ';

    printf("%c\n", chr);
 }

Depending on the file used, the output will be a blank, @, or + in exactly the same manner ls -l displays it. Hope this helps !

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!