I tried to simulate the linux file permission use st_mode, but when I print the result, it has an additional unwanted message.
/* file permission */
char buf[9] = {0};
char tmp_buf[] = "rwxrwxrwx";
int i;
for(i = 0; i < 9; i++) {
if (sta.st_mode & (1 << (8 - i))) buf[i] = tmp_buf[i];
else buf[i] = '-';
}
printf("%s", buf);
Here is my code, but the result is something like 'rw-rw-r--rwxrwxrwx' and the strlen(buf) is 18.... Can someone help? I am not sure why temp_buf is appended to 'buf'
The conversion specifier %s
expects an argument that represents a string. However it seems that the array buf
does not contain a string.
Either enlarge the array with one more byte for the terminating zero
char buf[10] = {0};
or just use (specifying the precision before the conversion symbol s
)
printf("%.9s", buf);
or alternatively
printf( "%.*s", ( int )sizeof( buf ), buf );