Here is the C program to implement the LS command Used in Linux

  • 3.5K
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    3.5K
    Shares

Even though the GUI in the Linux has come a long way over the past few years, the terminal always beats the GUI in terms of its raw power and usability. One of the most commonly used Linux commands is the ls command. The “ls” is a Linus shell command is which is used to print all the files and directories in the present directory in the form of a list.

# ls

0001.pcap        Desktop    Downloads         index.html   install.log.syslog  Pictures  Templates
anaconda-ks.cfg  Documents  fbcmd_update.php  install.log  Music               Public    Videos

This command can also be used in many ways by just tweaking the letters and symbols with it. Some examples are:

-> ls -l (-l is a character, not one) shows file or directory, modified date and time, size, file or folder name and also owner of file and it’s permission.

-> To see the list including hidden files, use ls -a. 

-> Use -lh option to see sizes in human readable format.

Now that we know the usefulness of this command, its time for us to know what we came here for:

C program to implement the LS command

  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<stdlib.h>
  4. #include<dirent.h>
  5. int main(int argc,char **argv)
  6. {
  7. struct dirent **namelist;
  8. int n;
  9. if(argc < 1)
  10. {
  11. exit(EXIT_FAILURE);
  12. }
  13. else if (argc == 1)
  14. {
  15. n=scandir(“.”,&namelist,NULL,alphasort);
  16. }
  17. else
  18. {
  19. n = scandir(argv[1], &namelist, NULL, alphasort);
  20. }
  21. if(n < 0)
  22. {
  23. perror(“scandir”);
  24. exit(EXIT_FAILURE);
  25. }
  26. else
  27. {
  28. while (n–)
  29. {
  30. printf(“%s\n”,namelist[n]->d_name);
  31. free(namelist[n]);
  32. }
  33. free(namelist);
  34. }
  35. exit(EXIT_SUCCESS);
  36. }

We hope you learnt something new today.

I do not claim the ownership of this code, as it was sourced form here.

The following two tabs change content below.

William Fieldhouse

I currently work full time as a penetration tester and have been involved within the IT security industry for over a decade. I also love to pioneer any forms of new technology and ideologies for future advancements. Feel free to contact me at [email protected]

  • 3.5K
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    3.5K
    Shares

William Fieldhouse

I currently work full time as a penetration tester and have been involved within the IT security industry for over a decade. I also love to pioneer any forms of new technology and ideologies for future advancements. Feel free to contact me at [email protected]

Leave a Reply