【问题标题】:How is this while-loop iterating?这个while循环如何迭代?
【发布时间】:2021-02-18 09:38:45
【问题描述】:
#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);
}

我了解这里的大部分代码,但我无法弄清楚 dp 每次如何更改/迭代。我以为可能是dp = readdir(dirp),就是每次都把dp的值赋值给另一个目录入口,但是我不确定,如果是,它是如何自动赋值给下一个的?

【问题讨论】:

    标签: c linux while-loop posix


    【解决方案1】:

    在 C 中,= 和其他所有运算符一样是一个运算符。 a = b 将变量a 设置为值b,然后返回值b。因此,y = (x = 1) + 2 将 x 设置为 1,然后将 2 添加到该 1,然后将 y 设置为 3。readdirDIR* 作为参数,并且 DIR* 具有确定要读取哪个文件的内部状态.每次调用readdir 时,它都会返回下一个文件。请参阅文档here

    【讨论】:

      猜你喜欢
      • 2021-09-06
      • 1970-01-01
      • 2016-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-29
      • 2015-03-23
      相关资源
      最近更新 更多