UNIXworkcode

1 /* 2 * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 3 * Version 2, December 2004 4 * 5 * Copyright (C) 2017 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 // this example is 99.9% identical to the linux xattr example 28 29 int main(int argc, char **argv) { 30 if(argc != 2) { 31 fprintf(stderr, "Usage: %s <file>\n", argv[0]); 32 return -1; 33 } 34 35 char *path = argv[1]; 36 37 // get list of extended attribute names 38 char *list = malloc(BUF_LEN); 39 ssize_t len = listxattr(path, list, BUF_LEN, 0); 40 41 if(len == -1) { 42 switch(errno) { 43 case ERANGE: { 44 // buffer too, get size of attribute list 45 ssize_t newlen = listxattr(path, NULL, 0, 0); 46 if(newlen > 0) { 47 // second try 48 list = realloc(list, newlen); 49 len = listxattr(path, list, newlen, 0); 50 if(len != -1) { 51 // this time it worked 52 break; 53 } 54 } 55 } 56 default: perror("listxattr"); 57 free(list); 58 return -1; 59 } 60 } 61 62 // print list 63 int begin = 0; 64 for(int i=0;i<len;i++) { 65 if(list[i] == '\0') { 66 printf("%s\n", list + begin); 67 begin = i + 1; 68 } 69 } 70 71 free(list); 72 73 return 0; 74 } 75