C language base format output control length

  • 2020-05-17 06:06:31
  • OfStack

c language format output control length

Today, when implementing the ls command, the output file name is aligned up and down:


1  2  a.c  b  crawler text  The public   video   The document   music 
1.c 2.c a.out b.c git   win   The template    The picture   download   desktop 

I want to achieve alignment, and I think of the formatted output of c:


printf("%-10s",s);

This allows the string s to be left in 10 cells.

However, due to a difficult problem to solve, the 10 above cannot be paid in advance, which is calculated during the program running, so I wonder if it can be output like this:


int a=5;
char s[]="hell";
printf("%-%ds",a,s);

If it does not work in practice, other solutions must be found.

Then look at the format of printf, the format control of printf is in "", does that mean you can replace it with a string" ", then try:


char a[]="%05s";
char s[]="hello";
printf(a,s);

Successful output:


   hello

This seemed possible, and the code was written:


 int n=13;
  char na[3];
  if(n > 9) {
    na[0] = (n/10) + 48;
    na[1] = (n%10) + 48;
    na[2] = '\0';
  }
  else {
    na[0] = n + 48;
    na[1] = '\0';
  }
  char a[10]="%-";
  strcat(a,na);
  char s[]="s ";
  strcat(a,s);
  char b[]="hellow";
  puts(a);
  printf(a,b);

n is the maximum length of the file name that ls outputs (should not be greater than 99 by visual inspection).

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: