#include <stdio.h>
#include <dirent.h>
int main() {
struct dirent *de;
DIR *dr;
int i = 1;
dr = opendir("."); // need to get directory through stdin insted of this
if (dr == NULL) printf("Could not open directory");
while (((de = readdir(dr)) != NULL))
{
printf("\t%d. %s\n", i, de -> d_name);
i++;
}
closedir(dr);
return 0;
}
Asked
Active
Viewed 59 times
0

kiner_shah
- 3,939
- 7
- 23
- 37

Tomas
- 3
- 3
-
4How about `argv[1]` ? (seems the logical choice to me) – wildplasser Jun 16 '19 at 15:46
-
I am a newbie in coding, so i don't really understand what you mean. I just want program to work show list of files and sub-directories after this ./a.out < directory or pwd|./a.out – Tomas Jun 16 '19 at 15:50
-
2Maybe you mean int main(int argc, int *argv[]) ..... opendir(argv[1]); – Tomas Jun 16 '19 at 15:51
-
https://stackoverflow.com/questions/5157337/c-reading-command-line-parameters/5157549 may help. – Shubham Jun 16 '19 at 15:52
1 Answers
1
You read it from stdin and use in place of "."
. Here is the full example
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>
int main(){
struct dirent *de;
char dirbuf[BUFSIZ] = {0};
DIR *dr;
int i = 1;
puts("Chose the directory: ");
if (fgets(dirbuf, BUFSIZ, stdin) == NULL) {
perror("fgets");
exit(-1);
}
dirbuf[strlen(dirbuf)-1] = '\0'; // remove \n
dr = opendir(dirbuf); // need to get directory through stdin insted of this
if (dr == NULL) {
perror("opendir");
exit(-1);
}
while(((de = readdir(dr)) != NULL))
{
printf("\t%d. %s\n", i, de -> d_name);
i++;
}
closedir(dr);
return 0;
}

geckos
- 5,687
- 1
- 41
- 53
-
1Safer removal of (possible) trailing *ENTER*: `dirbuf[strcspn(dirbuf, "\n\r")] = 0;` – pmg Jun 17 '19 at 07:49
-
Suggestion: initialize `i` with `0` and swap the statements inside the `while`. Reason is that after the while `i` has the number of entries printed (no real advantage in this short program but may be easier with longer programs). – pmg Jun 17 '19 at 07:53