c++ - testing directory S_ISDIR acts inconsistently -


I am doing simple tests on all the files in the directory but for some reason, sometimes, they behave incorrectly? What's wrong with my code?

  using namespace std; Int main () {string s = "/ home /"; Struct dirent * file; DIR * dir = opendir (s.c_str ()); While ((file = readdir (dir)) = = null) {struct stat * file_info = New (straight state); State (file & gt; d_name, file_info); If ((file_info-> st_mode and S_IFMT) == S_IFDIR) cout & lt; & Lt; "Deer" & lt; & Lt; Endl; And cout & lt; & Lt; "Other" & lt; & Lt; Endl; } Monkey (DIR); }  

You made some mistakes, call the most important stat ) without checking its return value. I have modified your program:

  #include & lt; Cstdio & gt; # Include & lt; Dirent.h & gt; # Include & lt; Iostream & gt; #include & lt; String & gt; # Include & lt; Sys / stat.h & gt; using namespace std; Int main () {string s = "/ home /"; Struct dirent * file; DIR * dir = opendir (s.c_str ()); While ((file = readdir (dir)) = NULL) {struct stat file_info; If (stat (file-> D_N, and file_infof) == -1) {mirror ("state"); Return 1; } If (S_ISDIR (file_info.st_mode)) cout & lt; & Lt; "Deer" & lt; & Lt; File-> D_name & lt; & Lt; Endl; And cout & lt; & Lt; "Other" & lt; & Lt; File-> D_name & lt; & Lt; Endl; } Monkey (DIR); }  

When I ran it, I found this output:

  $ ./a.exe dir Dir .. stat: No such file or directory I have now seen that the  stat  was called by the file name of  Roland , which is not present in my current working directory. You need to prefix the file names with a directory name. 

Your second bug was to assign a new struct stat all the time, but not to free the memory after use. By default, C ++ does not contain garbage collection. , So your program will soon be out of memory.


Comments