Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This code has several problems. First, when you perform the <code>strcmp</code> to check if <code>d_name</code> is "." or "..", you need to use an OR, not an AND. Second, when you call <code>sprintf</code> to create your c-string <code>path</code>, you should not have a newline at the end of the string. This is what was causing your code to only go one level deep. Third, when you call <code>get_current_dir_name</code>, it does all the <code>malloc</code> work for you. What you're doing is allocating space for a single char, which won't work in itself and is not a correct use of the API. See the <a href="http://linux.die.net/man/3/get_current_dir_name" rel="nofollow">man page for get_current_dir_name</a>.</p> <p>The below code addresses these issues (and also has proper indentation).</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; #include &lt;dirent.h&gt; #include &lt;limits.h&gt; #include &lt;string.h&gt; int directories=0; void walkThroughDirectory(char *directory_name,char *searchString) { DIR *directory; struct dirent *walker; char d_name[PATH_MAX]; int path_length; char path[PATH_MAX]; directory = opendir(directory_name); if(directory == NULL) { std::cout &lt;&lt; directory_name &lt;&lt; " Cannot be Opened" &lt;&lt; std::endl; exit(1); } while((walker=readdir(directory)) != NULL) { strcpy(d_name, walker-&gt;d_name); // Needs to be || not &amp;&amp; if (strcmp(d_name, "..") == 0 || strcmp(d_name, ".") == 0) { continue; } else { // No newline on the path name. path_length = snprintf(path, PATH_MAX, "%s/%s", directory_name, d_name); if (path_length &gt;= PATH_MAX) { std::cout &lt;&lt; "Path is too long" &lt;&lt; std::endl; exit(2); } if(walker-&gt;d_type == DT_DIR) { directories++; walkThroughDirectory(path, searchString); } else if(walker-&gt;d_type==DT_REG) { std::ifstream openFile; openFile.open(path); char line[1500]; int currentLine = 0; if (openFile.is_open()) { while (openFile.good()) { currentLine++; openFile.getline(line, 1500); if (strstr(line, searchString) != NULL) std::cout &lt;&lt; path &lt;&lt; ": " &lt;&lt; currentLine &lt;&lt; ": " &lt;&lt; line &lt;&lt; std::endl; } } openFile.close(); } } } if (closedir(directory)) { std::cout &lt;&lt; "Unable to close " &lt;&lt; directory_name &lt;&lt; std::endl; exit(3); } } int main() { // get_current_dir_name() mallocs a string for you. char *name; name = get_current_dir_name(); walkThroughDirectory(name, "matthew"); free(name); std::cout &lt;&lt; "Total Directories: " &lt;&lt; directories &lt;&lt; std::endl; return 0; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload