首页 > 后端开发 > C++ > 正文

如何使用C/C++获取目录中的文件列表?

王林
发布: 2023-09-09 21:41:02
转载
1074人浏览过

如何使用c/c++获取目录中的文件列表?

标准 C++ 没有提供执行此操作的方法。您可以使用系统命令来初始化 ls 命令,如下所示 -

示例

#include<iostream>
int main () {
   char command[50] = "ls -l";
   system(command);
   return 0;
}
登录后复制

输出

这将给出输出 -

-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
登录后复制

如果您使用的是 Windows,则可以使用 dir 而不是 ls 来显示列表。

示例

您可以使用直接包(https://github.com/dir/ls)。 com/tronkko/dirent)以使用更灵活的 API。您可以按如下方式使用它来获取文件列表 -

笔目鱼英文论文写作器
笔目鱼英文论文写作器

写高质量英文论文,就用笔目鱼

笔目鱼英文论文写作器 87
查看详情 笔目鱼英文论文写作器

立即学习C++免费学习笔记(深入)”;

#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");
}
登录后复制

输出

这将给出输出 -

a.out
hello.cpp
hello.py
hello.o
hydeout
my_file.txt
watch.py
登录后复制

以上就是如何使用C/C++获取目录中的文件列表?的详细内容,更多请关注php中文网其它相关文章!

相关标签:
c++速学教程(入门到精通)
c++速学教程(入门到精通)

c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号