打开目录后如何读取目录中的内容?

问题描述 投票:1回答:1

为什么我不能读取目录中的内容,它不断给我带来分段错误?

#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);
}
c directory
1个回答
1
投票

这里定义大小为0的数组。

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

这里(当ifiles都为0时,您将访问数组中那些零(在这里有冲突吗?)元素中的第一个。

names[i] = file->d_name;

然后您增加files

files++;

但是,这不会更改数组的大小,即使这样做也为时已晚。

继续,我将引用WhozCraigs的有用评论(经许可):

即使修复该问题,您仍然需要唤醒。 names[i] = file->d_name将存储一个指向内存的指针,该指针在枚举的生命周期内既不能保证也不可能是静态的。枚举每个文件条目时,它可以/将被重用。即使不是这样,一旦closedir被触发,所有的内存也将被保证是不可用的。如果要保留文件名,则需要复制它们。不只是保存指针。

报价结束。

© www.soinside.com 2019 - 2024. All rights reserved.