Home > Backend Development > C++ > How to get a list of files in a directory using C/C++?

How to get a list of files in a directory using C/C++?

王林
Release: 2023-09-09 21:41:02
forward
878 people have browsed it

How to get a list of files in a directory using C/C++?

Standard C provides no way to do this. You can use the system command to initialize the ls command as shown below -

Example

#include<iostream>
int main () {
   char command[50] = "ls -l";
   system(command);
   return 0;
}
Copy after login

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
Copy after login

If you If you are using Windows, you can use dir instead of ls to display the list.

Example

You can use the direct package (https://github.com/dir/ls). com/tronkko/dirent) to use a 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");
}
Copy after login

output

This will give the output -

a.out
hello.cpp
hello.py
hello.o
hydeout
my_file.txt
watch.py
Copy after login

The above is the detailed content of How to get a list of files in a directory using C/C++?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template