第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

為什么stat使用readdir中的名稱失?。?/h1>

我編寫了一個(gè)打印目錄名或文件名的程序。很簡單,但是我遇到了麻煩。它無法區(qū)分目錄和文件類型。我知道,我用stat.st_mode完成了。但是出了點(diǎn)問題:當(dāng)我使用gdb檢查st_mode值時(shí),我發(fā)現(xiàn)它是0,但“?!背?。和“ ..”,所以這里是一個(gè)問題:為什么st_mode為0?那就是我的代碼:#include <stdio.h>#include <stdlib.h>#include <dirent.h>#include <sys/stat.h>int main(void){    DIR *pDir = opendir("MyDirectory");    struct dirent *pDirent;    struct stat vStat;    if (pDir == NULL)    {        printf("Can't open the directory \"MyDirectory\"");        exit(1);    }    while ((pDirent = readdir(pDir)) != NULL)    {        stat(pDirent->d_name, &vStat);        if (S_ISDIR(vStat.st_mode))            printf("Directory: %s\n", pDirent->d_name);        else            printf("File: %s\n", pDirent->d_name);    }    closedir(pDir);    return 0;}
查看完整描述

2 回答

?
慕后森

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊

經(jīng)典readdir錯(cuò)誤:pDirent->d_name是目錄條目的名稱,而不是文件的路徑。這"1","4-5.c"等于是你的stat電話正在尋找該名稱的文件在當(dāng)前目錄中,而不是下MyDirectory。


檢查的返回值stat。您會(huì)看到它是ENOENT- .和和..,除了在當(dāng)前目錄中也存在。當(dāng)stat出現(xiàn)故障時(shí),stat結(jié)構(gòu)的內(nèi)容是不確定的。


如果您opendir在以外的目錄中進(jìn)行調(diào)用,.則要對(duì)返回的名稱執(zhí)行幾乎所有有用的操作,您需要構(gòu)建完整路徑。將傳遞到的路徑復(fù)制opendir到緩沖區(qū)中,該緩沖區(qū)要有足夠的空間以容納斜杠和文件名,然后將每個(gè)文件名復(fù)制到該緩沖區(qū)。概念驗(yàn)證代碼(省略錯(cuò)誤檢查等):


char *directory = "MyDirectory";

size_t directory_length = strlen(directory);

char *path = malloc(directory_length + 1 + NAME_MAX);

strcpy(path, directory);

path[directory_length] = '/';

while ((pDirent = readdir(pDir)) != NULL) {

    strcpy(path + directory_length + 1, pDirent->d_name);

    if (stat(path, &vStat) == -1) {

        perror(path);

        continue;

    }

    …

}


查看完整回答
反對(duì) 回復(fù) 2019-11-21
?
躍然一笑

TA貢獻(xiàn)1826條經(jīng)驗(yàn) 獲得超6個(gè)贊

請(qǐng)注意,使用該方法是chdir()有效的,但是如果您需要在一個(gè)命令中處理多個(gè)目錄,可能會(huì)給您帶來麻煩。您如何回到起點(diǎn)?(一個(gè)答案是fchdir() -其他答案要復(fù)雜得多。

查看完整回答
反對(duì) 回復(fù) 2019-11-21
  • 2 回答
  • 0 關(guān)注
  • 833 瀏覽
慕課專欄
更多

添加回答

了解更多

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)