Search code examples
clinuxwhile-loopposix

How is this while-loop iterating?


#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <errno.h>

#define ERR(source) (perror(source),\
        fprintf(stderr, "%s:%d\n", __FILE__, __LINE__),\
        exit(EXIT_FAILURE))

void scan_dir() {
    DIR* dirp;
    struct dirent *dp;
    struct stat filestat;
    if (NULL == (dirp = opendir("."))) ERR("opendir");

    do {
        errno = 0;
        if ((dp = readdir(dirp)) != NULL) {
            if (lstat(dp->d_name, &filestat)) ERR("lstat");
            printf("%s\n", dp->d_name);
        }
    }
    while (dp != NULL);
}

I understand most of the code here, but I couldn't figure out how the dp changes/iterates every time. I thought that maybe it is dp = readdir(dirp), that is assigning dp's value to another directory entrance every time, but I am not sure, and if it is, how it automatically assigns it to the next one?


Solution

  • In C, = is an operator just like every other operator. a = b sets the variable a to the value b, then returns the value b. So, y = (x = 1) + 2 sets x to 1, then adds 2 to that 1, then sets y to 3. readdir takes a DIR* as an argument, and that DIR* has an internal state that determines which file to read. Every time you call readdir on it, it'll return the next file. See the docs here.