🛠️🐜 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.

110 lines
2.3 KiB

  1. /*
  2. * Example program demonstrating the use of scandir function.
  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. * scandir "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. * Copyright (C) 1998-2019 Toni Ronkko
  20. * This file is part of dirent. Dirent may be freely distributed
  21. * under the MIT license. For all details and documentation, see
  22. * https://github.com/tronkko/dirent
  23. */
  24. #define _CRT_SECURE_NO_WARNINGS
  25. #include <stdio.h>
  26. #include <stdlib.h>
  27. #include <string.h>
  28. #include <dirent.h>
  29. #include <errno.h>
  30. #include <locale.h>
  31. static void list_directory (const char *dirname);
  32. int
  33. main(
  34. int argc, char *argv[])
  35. {
  36. int i;
  37. /* Select default locale */
  38. setlocale (LC_ALL, "");
  39. /* For each directory in command line */
  40. i = 1;
  41. while (i < argc) {
  42. list_directory (argv[i]);
  43. i++;
  44. }
  45. /* List current working directory if no arguments on command line */
  46. if (argc == 1) {
  47. list_directory (".");
  48. }
  49. return EXIT_SUCCESS;
  50. }
  51. /*
  52. * List files and directories within a directory.
  53. */
  54. static void
  55. list_directory(
  56. const char *dirname)
  57. {
  58. struct dirent **files;
  59. int i;
  60. int n;
  61. /* Scan files in directory */
  62. n = scandir (dirname, &files, NULL, alphasort);
  63. if (n >= 0) {
  64. /* Loop through file names */
  65. for (i = 0; i < n; i++) {
  66. struct dirent *ent;
  67. /* Get pointer to file entry */
  68. ent = files[i];
  69. /* Output file name */
  70. switch (ent->d_type) {
  71. case DT_REG:
  72. printf ("%s\n", ent->d_name);
  73. break;
  74. case DT_DIR:
  75. printf ("%s/\n", ent->d_name);
  76. break;
  77. case DT_LNK:
  78. printf ("%s@\n", ent->d_name);
  79. break;
  80. default:
  81. printf ("%s*\n", ent->d_name);
  82. }
  83. }
  84. /* Release file names */
  85. for (i = 0; i < n; i++) {
  86. free (files[i]);
  87. }
  88. free (files);
  89. } else {
  90. fprintf (stderr, "Cannot open %s (%s)\n", dirname, strerror (errno));
  91. exit (EXIT_FAILURE);
  92. }
  93. }