🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
2.3 KiB

  1. /*
  2. * An example demonstrating basic directory listing.
  3. *
  4. * Compile this file with Visual Studio and run the produced command in
  5. * console with a directory name argument. For example, command
  6. *
  7. * ls "c:\Program Files"
  8. *
  9. * might output something like
  10. *
  11. * ./
  12. * ../
  13. * 7-Zip/
  14. * Internet Explorer/
  15. * Microsoft Visual Studio 9.0/
  16. * Microsoft.NET/
  17. * Mozilla Firefox/
  18. *
  19. * The ls command provided by this file is only an example: the command does
  20. * not have any fancy options like "ls -al" in Linux and the command does not
  21. * support file name matching like "ls *.c".
  22. *
  23. * Copyright (C) 1998-2019 Toni Ronkko
  24. * This file is part of dirent. Dirent may be freely distributed
  25. * under the MIT license. For all details and documentation, see
  26. * https://github.com/tronkko/dirent
  27. */
  28. #define _CRT_SECURE_NO_WARNINGS
  29. #include <stdio.h>
  30. #include <stdlib.h>
  31. #include <string.h>
  32. #include <dirent.h>
  33. #include <errno.h>
  34. #include <locale.h>
  35. static void list_directory (const char *dirname);
  36. int
  37. main(
  38. int argc, char *argv[])
  39. {
  40. int i;
  41. /* Select default locale */
  42. setlocale (LC_ALL, "");
  43. /* For each directory in command line */
  44. i = 1;
  45. while (i < argc) {
  46. list_directory (argv[i]);
  47. i++;
  48. }
  49. /* List current working directory if no arguments on command line */
  50. if (argc == 1) {
  51. list_directory (".");
  52. }
  53. return EXIT_SUCCESS;
  54. }
  55. /*
  56. * List files and directories within a directory.
  57. */
  58. static void
  59. list_directory(
  60. const char *dirname)
  61. {
  62. DIR *dir;
  63. struct dirent *ent;
  64. /* Open directory stream */
  65. dir = opendir (dirname);
  66. if (dir != NULL) {
  67. /* Print all files and directories within the directory */
  68. while ((ent = readdir (dir)) != NULL) {
  69. switch (ent->d_type) {
  70. case DT_REG:
  71. printf ("%s\n", ent->d_name);
  72. break;
  73. case DT_DIR:
  74. printf ("%s/\n", ent->d_name);
  75. break;
  76. case DT_LNK:
  77. printf ("%s@\n", ent->d_name);
  78. break;
  79. default:
  80. printf ("%s*\n", ent->d_name);
  81. }
  82. }
  83. closedir (dir);
  84. } else {
  85. /* Could not open directory */
  86. fprintf (stderr, "Cannot open %s (%s)\n", dirname, strerror (errno));
  87. exit (EXIT_FAILURE);
  88. }
  89. }