簡體   English   中英

更改路徑類型時stat返回錯誤

[英]stat returning error when changing path type

我正在嘗試檢查文件是否是文件夾,但是當我更改此行時:

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(...)失敗。 盡管兩條線都生成相同的輸出路徑。

這是怎么回事?


編碼:

#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;
}

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系統上), sizeof(size_t) > sizeof(int)是必需的。 *消耗的值是一個int

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM