Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You need to check the return status of your system calls, and specifically <code>stat()</code>.</p> <p>What's happening is that you read a name found in the <code>..</code> directory, but when you invoke <code>stat()</code>, you are doing so on <code>./name</code> and not <code>../name</code>.</p> <p>This code should demonstrate the point:</p> <pre><code>#include &lt;dirent.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;sys/stat.h&gt; #include &lt;unistd.h&gt; #include &lt;errno.h&gt; void print_dir(char *dir_n, char *file) { DIR *dir = opendir(dir_n); if (dir == 0) { int errnum = errno; fprintf(stderr, "error: opendir(\"%s\") failed (%d: %s)\n", dir_n, errnum, strerror(errnum)); exit(1); } struct dirent *Dirent; while ((Dirent = readdir(dir)) != 0) { struct stat stats; if (stat(Dirent-&gt;d_name, &amp;stats) &lt; 0) { int errnum = errno; fprintf(stderr, "error: failed to stat(\"%s\") (%d: %s)\n", Dirent-&gt;d_name, errnum, strerror(errnum)); } else if (S_ISDIR(stats.st_mode)) { if (strcmp(file, Dirent-&gt;d_name) == 0) { printf("found directory %s (inode = %ld)\n", Dirent-&gt;d_name, (long)stats.st_ino); break; } else printf("found directory %s - not a match for %s\n", Dirent-&gt;d_name, file); } else { printf("%s is not a directory\n", Dirent-&gt;d_name); } } closedir(dir); } int main(void) { print_dir("..", "dirtest"); return 0; } </code></pre> <p>And this trivial variant should find the directory <code>../dirtest</code> if it exists:</p> <pre><code>#include &lt;dirent.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;sys/stat.h&gt; #include &lt;unistd.h&gt; #include &lt;errno.h&gt; void print_dir(char *dir_n, char *file) { DIR *dir = opendir(dir_n); if (dir == 0) { int errnum = errno; fprintf(stderr, "error: opendir(\"%s\") failed (%d: %s)\n", dir_n, errnum, strerror(errnum)); exit(1); } struct dirent *Dirent; while ((Dirent = readdir(dir)) != 0) { char fullname[1024]; snprintf(fullname, sizeof(fullname), "%s/%s", dir_n, Dirent-&gt;d_name); struct stat stats; if (stat(fullname, &amp;stats) &lt; 0) { int errnum = errno; fprintf(stderr, "error: failed to stat(\"%s\") (%d: %s)\n", fullname, errnum, strerror(errnum)); } else if (S_ISDIR(stats.st_mode)) { if (strcmp(file, Dirent-&gt;d_name) == 0) { printf("found directory %s (%s) (inode = %ld)\n", Dirent-&gt;d_name, fullname, (long)stats.st_ino); break; } else printf("found directory %s - not a match for %s\n", fullname, file); } else { printf("%s is not a directory\n", fullname); } } closedir(dir); } int main(void) { print_dir("..", "dirtest"); 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