Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to get a list of all the files and sub-directories of the current working directory in C

2 Answers

0 votes
#include <stdio.h>
#include <stdlib.h>
 
int main(void) {
	system("dir");
}
     
 
      
/*
run:
       
 Volume in drive C has no label.
 Volume Serial Number is 1234-ABCD

 Directory of C:\...\test\test-project\Debug

07/03/2020  12:21 PM    <DIR>          .
07/03/2020  12:21 PM    <DIR>          ..
07/03/2020  12:21 PM                 5 .d
02/14/2020  12:47 PM                 4 data.bin
06/23/2020  10:06 PM               406 file.c
07/03/2020  12:20 PM             2,143 main.c.o
07/03/2020  12:20 PM                24 main.c.o.d
02/14/2020  07:39 PM               336 product_file.dat
07/03/2020  12:21 PM           133,817 test-project.exe
               7 File(s)        136,735 bytes
               2 Dir(s)  847,758,987,264 bytes free
  
*/

 



answered Jul 3, 2020 by avibootz
0 votes
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <limits.h>

void listFiles(const char *path)
{
    struct dirent *dn;
    DIR *dir = opendir(path);

    if (!dir) 
        return; 

    while ((dn = readdir(dir)) != NULL) {
        printf("%s\n", dn->d_name);
    }

    closedir(dir);
}

int main()
{
	char working_directory[PATH_MAX];
     
	if (getcwd(working_directory, sizeof(working_directory)) != NULL) {
		listFiles(working_directory);
	} else {
		perror("getcwd() error");
		return 1;
	}

	

    return 0;
}



/*
run:

.
..
.d
data.bin
file.c
main.c.o
main.c.o.d
product_file.dat
test-project.exe
  
*/
 

 



answered Jul 3, 2020 by avibootz

Related questions

...