

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can I get the list of files in a directory using C/C++?
Standard C++ doesn't provide a way to do this. You could use the system command to initialize the ls command as follows −
Example
#include<iostream> int main () { char command[50] = "ls -l"; system(command); return 0; }
Output
This will give the output −
-rwxrwxrwx 1 root root 9728 Feb 25 20:51 a.out -rwxrwxrwx 1 root root 131 Feb 25 20:44 hello.cpp -rwxrwxrwx 1 root root 243 Sep 7 13:09 hello.py -rwxrwxrwx 1 root root 33198 Jan 7 11:42 hello.o drwxrwxrwx 0 root root 512 Oct 1 21:40 hydeout -rwxrwxrwx 1 root root 42 Oct 21 11:29 my_file.txt -rwxrwxrwx 1 root root 527 Oct 21 11:29 watch.py
If you're on windows, you can use dir instead of ls to display the list.
Example
You can use the direct package(https://github.com/tronkko/dirent) to use a much more flexible API. You can use it as follows to get a list of files −
#include <iostream> #include <dirent.h> #include <sys/types.h> using namespace std; void list_dir(const char *path) { struct dirent *entry; DIR *dir = opendir(path); if (dir == NULL) { return; } while ((entry = readdir(dir)) != NULL) { cout << entry->d_name << endl; } closedir(dir); } int main() { list_dir("/home/username/Documents"); }
Output
This will give the output −
a.out hello.cpp hello.py hello.o hydeout my_file.txt watch.py
- Related Questions & Answers
- How can I get the list of files in a directory using C or C++?
- How do I list all files of a directory in Python?
- How to get the list of jpg files in a directory in Java?
- How can I list the contents of a directory in Python?
- How to list down all the files available in a directory using C#?
- How to list all files in a directory using Java?
- How can I iterate over files in a given directory in Python?
- How to list out the hidden files in a Directory using Java program?
- How to list all files (only) from a directory using Java?
- How to get all the files, sub files and their size inside a directory in C#?
- How can I create directory tree using C++ in Linux?
- Using SAP ABAP, how can I read content of CSV files in a directory to an internal table?
- How to list the hidden files in a directory in Java?
- How to get a list of all sub-directories in the current directory using Python?
- How can I get a list of locally installed Python modules?
Advertisements