
標準 C にはこれを行う方法がありません。以下に示すように、システム コマンドを使用して ls コマンドを初期化できます。 -
Example
1 2 3 4 5 6 | # include <iostream>
int main () {
char command[50] = "ls -l" ;
system(command);
return 0;
}
|
ログイン後にコピー
Output
これにより、出力が得られます-
1 2 3 4 5 6 7 | -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 Windows を使用している場合は、ls の代わりに dir を使用してリストを表示できます。
例
ダイレクト パッケージ (https://github.com/dir/ls) を使用できます。 com/tronkko/dirent) を使用して、より柔軟な API を使用します。次のように使用して、ファイルのリストを取得できます -
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | # 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
これにより、出力 -
1 2 3 4 5 6 7 | a.out
hello.cpp
hello.py
hello.o
hydeout
my_file.txt
watch.py
|
ログイン後にコピー
が得られます。
以上がC/C++を使用してディレクトリ内のファイルのリストを取得するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。