UNIXworkcode

 1  /*
 2   *             DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
 3   *                     Version 2, December 2004
 4   * 
 5   *  Copyright (C) 2016 Olaf Wintermann <olaf.wintermann@gmail.com>
 6   * 
 7   *  Everyone is permitted to copy and distribute verbatim or modified
 8   *  copies of this license document, and changing it is allowed as long
 9   *  as the name is changed.
10   * 
11   *             DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
12   *    TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
13   * 
14   *   0. You just DO WHAT THE FUCK YOU WANT TO.
15   */
16  
17  #include <sys/types.h>
18  #include <sys/xattr.h>
19  #include <unistd.h>
20  #include <stdio.h>
21  #include <stdlib.h>
22  #include <string.h>
23  #include <errno.h>
24  
25  #define BUF_LEN 1024
26  
27  int main(int argc, char **argv) {
28      if(argc != 2) {
29          fprintf(stderr, "Usage: %s <file>\n", argv[0]);
30          return -1;
31      }
32      
33      char *path = argv[1];
34      
35      // get list of extended attribute names
36      char *list = malloc(BUF_LEN);
37      ssize_t len = listxattr(path, list, BUF_LEN);
38      
39      if(len == -1) {
40          switch(errno) {
41              case ERANGE: {
42                  // buffer too, get size of attribute list
43                  ssize_t newlen = listxattr(path, NULL, 0);
44                  if(newlen > 0) {
45                      // second try
46                      list = realloc(list, newlen);
47                      len = listxattr(path, list, newlen);
48                      if(len != -1) {
49                          // this time it worked
50                          break;
51                      }
52                  }
53              }
54              default: perror("listxattr");
55              free(list);
56              return -1;
57          }
58      }
59      
60      // print list
61      int begin = 0;
62      for(int i=0;i<len;i++) {
63          if(list[i] == '\0') {
64              printf("%s\n", list + begin);
65              begin = i + 1;
66          }
67      }
68      
69      free(list);
70      
71      return 0;
72  }