簡體   English   中英

打開目錄后如何讀取目錄中的內容?

[英]How do you read what is in a directory after opening it?

為什么我不能讀取目錄中的內容,它一直給我分段錯誤?

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

int count(char* loc)
{
        int num = 0;
        char c;
        FILE *file = fopen(loc, "r");
        while( (c = fgetc(file)) != EOF) {
                if(c == '\n')
                        num++;
        }
        int r = fclose(file);
        return num;
}

int main()
{
        int lines = 0;
        int files = 0;
        char* names[files];
        int i = 0;
        DIR* d = opendir("./visual");    //You can change this bit

        struct dirent *file;
        while((file = readdir(d)) != NULL){
                i++;
                names[i] = file->d_name;
                files++;
                printf("%s\n", names[i]);
        }
        closedir(d);
        printf("__________\n");
        for(int i = 0;i < files;i++){
                printf("i = %d\n", i);

                lines = lines + count(names[i]);
        }
        printf("you have written %d lines of code", lines);
}

這里定義了一個大小為 0 的數組。

int files = 0;
char* names[files];

在這里(雖然ifiles都是 0),您訪問數組中的第一個零(注意這里的沖突?)元素。

names[i] = file->d_name;

然后你增加files

files++;

然而,這不會改變數組的大小,即使會為時已晚。

繼續,我將引用 WhozCraigs 有用的評論(經許可):

即使解決了這個問題,你仍然處於覺醒狀態。 names[i] = file->d_name將存儲一個指向內存的指針,該指針在枚舉的生命周期內既不能保證也不太可能是靜態的。
當您枚舉每個文件條目時,它可以/將被重用。 即使沒有,一旦 closeir 被觸發,所有這些內存都保證是禁止的。
如果要保留文件名,則需要復制它們; 不僅僅是保存指針。

報價結束。

暫無
暫無

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

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