Untitled

 avatar
unknown
plain_text
16 days ago
1.5 kB
3
Indexable
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <dirent.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <sys/stat.h>

#define ARRAY_SIZE(x) sizeof(x) / sizeof(x[0])

void string_init(char (*filepath), char (*cwd), size_t size){
    memset(filepath, '\0', size);
    strcpy(filepath, cwd);
}
void ls(char *cwd, size_t size){

    assert(getcwd(cwd, size) != NULL);

    DIR *dir = opendir(cwd);
    if(!dir){
        perror("opendir");
        return;
    }

    struct dirent *entry = NULL;
    struct stat filestat;
    char filepath[INT8_MAX];

    int i = 0;
    while(cwd[i] != '\0'){
        filepath[i] = cwd[i];
        i++;
    }

    while ((entry = readdir(dir)) != NULL) {
        if(strcmp(entry->d_name, "..") && strcmp(entry->d_name, ".")){
            strcat(filepath, "/");
            strcat(filepath, entry->d_name);
        }
        else if (!strcmp(entry->d_name, ".")){
            strcpy(filepath, cwd);
        }
        else{
            char *last_slash = strrchr(filepath, '/');
            if (last_slash) {
                *last_slash = '\0';
            }
        }
        // printf("file name: %s\n", entry->d_name);
        // printf("file path: %s\n", filepath);
        printf("%s\n", entry->d_name);
        lstat(filepath, &filestat);

        string_init(filepath, cwd, ARRAY_SIZE(filepath));
    }

    closedir(dir);
}
int main(int argc, char const *argv[])
{
    char cwd[INT8_MAX];
    ls(cwd, ARRAY_SIZE(cwd));

    return 0;
}
Editor is loading...
Leave a Comment