-1

Can anyone suggest me how to do a recursive search for a file with a certain extension using system calls?I should use opendir() but I don't quite understand how it works and how to use it recursively.

Mat
  • 202,337
  • 40
  • 393
  • 406
  • 2
    What don´t you understand in particular? Provide an example to show your where your issue is. – RobertS supports Monica Cellio May 11 '20 at 12:09
  • 1
    Maybe this will give you some idea how opendir works, https://github.com/b-k/21st-Century-Examples/blob/master/process_dir.c. – Shadowchaser May 11 '20 at 12:17
  • There is a difference between recursive (function calling itself) and iterative (function uses loop to perform several iterations of similar steps, eg. calling another function in a loop.) – ryyker May 11 '20 at 12:24
  • When asking a question about system calls (or other OS specific things), you should always specify exactly which operating system you are targeting. For instance, i know there's an `opendir()` function in glibc (which would suggest you're using linux), but since i'm not familiar with Windows i don't know whether or not there's a function of the same name there. Specifying the OS makes it much easier for people to give an appropriate answer. – Felix G May 11 '20 at 12:26
  • On Linux use [nftw(3)](http://man7.org/linux/man-pages/man3/nftw.3.html). – Basile Starynkevitch May 11 '20 at 15:53

1 Answers1

1

I should use opendir() but I don't quite understand how it works and how to use it recursively.

Idiomatically, opendir() is not used recursively, rather it is used in conjunction with readdir() in a loop, iteratively to list files, which can include other directories.

An example of using opendir(), and readdir() in a loop to find files. (from here)

This example is directly from the link with the exception of the strstr() call, used to pull out the files with the extension you are looking for. (See comment in code):

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

int main()
{
    DIR *folder;
    struct dirent *entry;
    int files = 0;

    folder = opendir(".");
    if(folder == NULL)
    {
        perror("Unable to read directory");
        return(1);
    }

    while(entry=readdir(folder))
    {
        files++;
        if(strstr(entry->d_name, ".csv"))//Added to illustrate 
                                         //(change csv to extension you are looking for)
        {
            printf("File %3d: %s\n",
                files,
                entry->d_name);
        }

    }

    closedir(folder);

    return(0);
}

If you did indeed mean recursively, there are some ideas how to do that here.

ryyker
  • 22,849
  • 3
  • 43
  • 87