0

My task is to write a another small version of LS command. I successful read a directory and stored names of files into an sorted array. My question is how do I print out them in a column format. And how to use system call ioctl() to help me with the format?

   $ ls
   file.txt       file2.txt      file5.txt      file8.txt
   file0.txt      file3.txt      file6.txt      file9.txt
   file1.txt      file4.txt      file7.txt
Termininja
  • 6,620
  • 12
  • 48
  • 49
stanlopfer
  • 73
  • 1
  • 2
  • 5
  • Use tabs for indentation and spaces for alignment. `ioctl` isn't related to formatting as far as I know. – bzeaman Oct 22 '14 at 14:10

1 Answers1

0

Assuming filenames is an array containing C strings with the filenames and filenames_size is the amount of C strings in that array.

char **filenames;
size_t filenames_size;
size_t filenames_len = 0;
for (size_t i = 0; i < filenames_size; ++i) {
    size_t len = strlen(filenames[i]);
    if (filenames_len < len) {
        filenames_len = len;
    }
}
for (size_t i = 0; i < filenames_size; ++i) {
    printf("rwxrwxrwx %-*s 10KB\n", filenames_len, filenames[i]);
}

printf can pad the string, which is what we do here. First get the longest filename, then use that to pad the rest.

bzeaman
  • 1,128
  • 11
  • 28
  • Thank you for your response Benno. But I just need to print out the names of a files in a column format. No other information about the files is required. For example, char *filename[] = {file1.txt, file2.txt..........file10.txt}. – stanlopfer Oct 22 '14 at 14:32
  • my professor tells me to use ioctl() as a hint to do the column format. – stanlopfer Oct 22 '14 at 14:36
  • I think I got your question wrong. I'll try and edit it as soon as possible. Look at this answer: http://stackoverflow.com/a/1022961/2703418 – bzeaman Oct 22 '14 at 14:37
  • @stanlopfer Look for the `TIOCGWINSZ` IO-control. It tells you how large the terminal window is. – fuz Oct 22 '14 at 15:40