readdir.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #include <dirent.h>
  2. #include <errno.h>
  3. #include <fcntl.h>
  4. #include <stdbool.h>
  5. #include <stdio.h>
  6. #include <string.h>
  7. #include <sys/stat.h>
  8. #include <sys/types.h>
  9. #include <unistd.h>
  10. #define TEST_DIR "tmp"
  11. #define TEST_FILE "__testfile__"
  12. /* return true if file_name exists, otherwise false */
  13. bool find_file(char* dir_name, char* file_name) {
  14. bool found = false;
  15. DIR* dir = opendir(dir_name);
  16. if (dir == NULL) {
  17. perror("opendir failed");
  18. return found;
  19. }
  20. struct dirent* dent = NULL;
  21. while (1) {
  22. errno = 0;
  23. dent = readdir(dir);
  24. if (dent == NULL) {
  25. if (errno == 0)
  26. break;
  27. perror("readdir failed");
  28. goto out;
  29. }
  30. if (strncmp(file_name, dent->d_name, strlen(file_name)) == 0) {
  31. found = true;
  32. break;
  33. }
  34. }
  35. out:
  36. closedir(dir);
  37. return found;
  38. }
  39. int main(int argc, const char** argv) {
  40. int rv = 0;
  41. int fd = 0;
  42. /* setup the test directory and file */
  43. rv = mkdir(TEST_DIR, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
  44. if (rv < 0 && errno != EEXIST) {
  45. perror("mkdir failed");
  46. return 1;
  47. }
  48. rv = unlink(TEST_DIR"/"TEST_FILE);
  49. if (rv < 0 && errno != ENOENT) {
  50. perror("unlink failed");
  51. return 1;
  52. }
  53. /* test readdir: should not find a file that we just deleted */
  54. if (find_file(TEST_DIR, TEST_FILE)) {
  55. perror("file " TEST_FILE " was unexpectedly found\n");
  56. return 1;
  57. }
  58. fd = open(TEST_DIR"/"TEST_FILE, O_CREAT | O_RDWR | O_EXCL, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
  59. if (fd < 0) {
  60. perror("open failed");
  61. return 1;
  62. }
  63. if (!find_file(TEST_DIR, TEST_FILE)) {
  64. perror("file " TEST_FILE " was not found\n");
  65. return 1;
  66. }
  67. rv = close(fd);
  68. if (rv < 0) {
  69. perror("close failed");
  70. return 1;
  71. }
  72. rv = unlink(TEST_DIR"/"TEST_FILE);
  73. if (rv < 0) {
  74. perror("unlink failed");
  75. return 1;
  76. }
  77. printf("test completed successfully\n");
  78. return rv;
  79. }