Anonymous
Anonymous

Reputation: 11

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

Why can't I read what is in a directory, it keeps on giving me segmentation faults?

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

Upvotes: 1

Views: 56

Answers (1)

Yunnosch
Yunnosch

Reputation: 26703

Here you define an array of size 0.

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

Here (while i and files are both 0) you access the first of those zero (note the conflict here?) elements in the array.

names[i] = file->d_name;

Then you increase files.

files++;

This does however not change the size of the array, and even if it would it would be too late.

Going on, I will quote WhozCraigs helpful comment (with permission):

Even fixing that, you're still in for an awakening. names[i] = file->d_name will store off a pointer to memory that is neither guaranteed, nor even likely, to be static for the lifetime of the enumeration.
It can/will be reused as you enumerate each file entry. And even if it didn't, all that memory is guaranteed to be off-limits once closedir is fired.
If you want to retain the file names, you need to make copies of them; not just save off pointers.

End of quote.

Upvotes: 1

Related Questions