Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Suppose that <code>root/test</code> contains a file called <code>foo</code>. The call to <code>dent=readdir(dir)</code> sets <code>dent-&gt;d_name</code> to <code>"foo"</code>. You already have debugging output that shows this: <code>printf(dent-&gt;d_name)</code>¹. Then you try to open <code>foo</code> with <code>fopen</code>, but the file is actually <code>root/test/foo</code>. So this fails every time (unless you happen to also have a file called <code>foo</code> in the current directory).</p> <p>There are two ways to open the right file:</p> <ul> <li><p>Construct the full name of the file by concatenating the argument to <code>opendir</code> with the file name. Something like:</p> <pre><code>/*before */ size_t dir_length = strlen(DIR_PATH); char *filename = malloc(dir_length + NAME_MAX + 2); /*error checking omitted*/ strcpy(filename, DIR_PATH); filename[dir_length] = '/'; filename[dir_length+1] = 0; while ((dent = readdir(dir)) != NULL) { strcpy(filename + dir_length + 1, dent-&gt;d_name); /*now call lstat, fopen, etc. on filename*/ </code></pre></li> <li><p>Change into the directory you're listing. For example, change the opendir call to</p> <pre><code>chdir(DIR_PATH); /*error checking omitted*/ dir = opendir("."); </code></pre> <p>You have to remember to save the previous directory with <code>getcwd</code> and <code>chdir</code> back to it afterwards. This method is not recommended in production software because it is possible to have a current directory that you can't <code>chdir</code> back into due to permissions.</p></li> </ul> <p><a href="https://stackoverflow.com/questions/3536781/accessing-directories-in-c/3536853#3536853">slacker has already explained why <code>fopen</code> can't be used to test if a file is a directory.</a></p> <p><sub> ¹ which by the way should be <code>puts(dent-&gt;d_name)</code> or even better <code>fputs(dent-&gt;d_name, stderr)</code>: your original <code>printf</code> call would break if a file name contains <code>%</code>, which is not a big problem for debugging output but is a bad habit to get into. </sub></p>
 

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