简体   繁体   中英

C language printf add additional useless message

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 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM