Question Details

No question body available.

Tags

c directory opendir

Answers (1)

January 8, 2026 Score: 0 Rep: 5,250 Quality: Low Completeness: 80%

In examining your query, and determination to utilize directory information opened in one function to be used in other subsequent functions, one would need to refine the functions to reference address information. Using your initial code as a starting point and giving due to the good comments, following is a refactored example of one path to perform such methods.

#include 
#include 
#include 
#include 

void opendir (DIR ** directory, char * directoryname) { directory = opendir (directory_name);

if (directory == NULL) { printf("Cannot open directory '%s'\n", directory_name); exit(1); } }

void read_dir (DIR directory) { struct dirent pDirent; while ((pDirent = readdir(directory)) != NULL) { if(strcmp(pDirent->d_name,".") == 0 || strcmp(pDirent->d_name,"..") == 0 || (pDirent->dname) == '.' ) {} else { printf("%s\n", pDirent->dname); } } }

int main(int argc, char argv[]) { DIR pDir = NULL;

opendir(&pDir, argv[1]);

readdir(pDir);

closedir(pDir);

return 0; }

A high level overview of this refactoring is as follows:

  • The directory pointer is initially defined in the "main" function.

  • The directory opening function is refactored to accept the memory location of the directory pointer and the directory name as a character array, so that this information can be used by your "opendir" function.

  • Subsequently, now that a directory pointer address has been derived, it can be passed as a parameter value to the "readdir" function.

  • And finally, once all of the functions have been processed, the connection to the directory is closed so as to make sure proper cleanup has occurred before the program ends.

Following is a test of the refactored code displaying the file information in the directory noted in code launch.

craig@Vera:~/CPrograms/Console/FileFun/bin/Release$ ./FileFun "."
FileFun
Nets.py
pterosurusfly.png
Movement.py
RockPaperScissors.py
catchingnet.png
fondo.png
What.py
canon.png

The takeaway of this example is to probably delve more into "C" tutorials as it pertains to usage of pointers to variables, files, structures, and so forth.