0

I'm trying to make a C programm which is intended to search files in a folder. It works fine in a small one, but once I test my program with the root folder "/", it gives me some issues...

The code :

#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void ouvrir_dossier(char* nom) {
    DIR *d;
    struct dirent *dir;
    d = opendir(nom);
    if (d) {
        while ((dir = readdir(d)) != NULL) {
            if(strcmp(dir->d_name, ".") != 0 && strcmp(dir->d_name, "..") != 0) {
                printf("%s, type: %d\n", dir->d_name, dir->d_type);
                if(dir->d_type == 4) { // if dir a folder
                    
                    char* nouv_nom = (char*)malloc(strlen(nom)*sizeof(char)+strlen(dir->d_name)*sizeof(char)+4);
                    
                    strcat(nouv_nom, nom);
                    strcat(nouv_nom, "/");
                    strcat(nouv_nom, dir->d_name);
                    
                    //printf("%s\n", nouv_nom);
                    ouvrir_dossier(nouv_nom);
                    
                    free(nouv_nom);
                }
            }
        }
    closedir(d);
    }
}

int main(int argc, char **argv) {
    ouvrir_dossier(argv[1]);
    return(0);
}

I tested the code with this command : "./prog /" the output is :

snap, type: 4
bare, type: 4
current, type: 10
5, type: 4
dev, type: 4
etc, type: 4
home, type: 4
lib, type: 4
media, type: 4
meta, type: 4
proc, type: 4
root, type: 4
run, type: 4
snap, type: 4
sys, type: 4
tmp, type: 4
usr, type: 4
var, type: 4
corrupted size vs. prev_size
Abandon (core dumped)

I also tested to change size of the variable "nouv_nom" (new_name) by adding 1000 to sizeof() in malloc(). The resultat didn't gave me errors but just too few files, which is incoherent because I test with "/".

Then, I decided to show the variable "nouv_nom" with printf and this is a snippet of the result (because there is a lot of lines) :

tmp, type: 4
މ�V//tmp
home, type: 4
މ�V//home
lost+found, type: 4
މ�V//lost+found
lib32, type: 10
dev, type: 4
މ�V//dev
TheHangel
  • 21
  • 1
  • The first `strcat(nouv_nom, nom);` should be `strcpy(nouv_nom, nom);` because the destination memory does not contain a valid C string. – Weather Vane Sep 18 '22 at 17:55

0 Answers0