Trouble understanding how to process C string

后端 未结 4 1370
粉色の甜心
粉色の甜心 2021-01-27 07:13

I\'m trying to use Mac OS X\'s listxattr C function and turn it into something useful in Python. The man page tells me that the function returns a string buffer, which is a \"si

4条回答
  •  有刺的猬
    2021-01-27 08:01

    So you guessed pretty much right.

    The listxattr function returns a bunch of null-terminated strings packed in next to each other. Since strings (and arrays) in C are just blobs of memory, they don't carry around any extra information with them (such as their length). The convention in C is to use a null character ('\0') to represent the end of a string.

    Here's one way to traverse the list, in this case changing it to a comma-separated list.

    int i = 0;
    for (; i < res; i++)
       if (buffer[i] == '\0' && i != res -1) //we're in between strings
           buffer[i] = ',';
    

    Of course, you'll want to make these into Python strings rather than just substituting in commas, but that should give you enough to get started.

提交回复
热议问题