更改路径类型时返回stat错误

时间:2012-08-05 19:17:05

标签: c path

我正在尝试检查文件是否是文件夹,但是当我更改此行时:

snprintf(buf, sizeof buf, "%s\\%s", path, e->d_name);
                             ^      ^
                             +------+ note the differences

对此:

snprintf(buf, sizeof buf, "%s\b%s", d->dd_name, e->d_name);
                             ^      ^
                             +------+ note the differences

由于stat(...)失败,因此不打印“is folder”或“is file”。虽然两条线都生成相同的输出路径。

怎么回事?


代码:

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

int main(int argc, char** argv) {
    DIR *d;
    struct dirent *e;
    struct stat fs;
    char*path = "C:\\Users\\Me\\Documents\\NetBeansProjects\\MyApp";
    d = opendir(path);
    if (d != NULL) {
        while (e = readdir(d)) {
            char buf[256];
            snprintf(buf, sizeof buf, "%s\\%s", path, e->d_name); // <- here
            printf("%s\n",buf);
            if (stat(buf, &fs) < 0) continue;
            if (S_ISDIR(fs.st_mode)) {
                printf("is folder");
            } else {
                printf("is file");
            }
        }
        closedir(d);
    }

    return 0;
}

1 个答案:

答案 0 :(得分:0)

来自Mat的建议是合理的; DIR结构中没有记录在案的可公开访问的成员,因此您不应该尝试使用d->dd_name

但是,如果要从字符串末尾删除星号,则无法使用退格键来执行此操作。退格仅在终端输入时删除字符。否则,它只是字符串中的控制字符。你可以使用:

snprintf(buf, sizeof(buf), "%.*s%s", (int)strlen(d->dd_name)-1, d->dd_name, e->d_name);

这将省略d->dd_name字符串中的最后一个字符(我假设是一个尾部斜杠或反斜杠)。请注意,在sizeof(size_t) > sizeof(int)时(如在64位Unix系统上),必须进行强制转换; *消耗的值为int