如何在C语言中跨平台扫描目录的文件和文件夹?
#define _XOPEN_SOURCE 700
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
int main (void)
{
DIR *dp;
struct dirent *ep;
dp = opendir ("./");
if (dp != NULL)
{
while ((ep = readdir (dp)) != NULL)
puts (ep->d_name);
(void) closedir (dp);
return 0;
}
else
{
perror ("Couldn't open the directory");
return -1;
}
}
来源: http://www.gnu.org/software/libtool/manual/libc/Simple-Directory-Lister.html
在Ubuntu 16.04中测试通过。
严格的回答是“你不能”,因为文件夹的概念并不是真正跨平台的。
在微软平台上,你可以使用 _findfirst、_findnext 和 _findclose 来获得 'c' 类似的感觉,以及 FindFirstFile 和 FindNextFile 来获取底层的 Win32 调用。
这里有 C-FAQ 的回答:
我创建了一个处理这个问题的开源(BSD)C头文件。它目前支持POSIX和Windows。请查看:
https://github.com/cxong/tinydir
tinydir_dir dir;
tinydir_open(&dir, "/path/to/dir");
while (dir.has_next)
{
tinydir_file file;
tinydir_readfile(&dir, &file);
printf("%s", file.name);
if (file.is_dir)
{
printf("/");
}
printf("\n");
tinydir_next(&dir);
}
tinydir_close(&dir);
#ifdef
解决方案。 - Joshua没有标准的C(或C ++)方法可以枚举目录中的文件。
在Windows下,您可以使用FindFirstFile / FindNextFile函数枚举目录中的所有条目。在Linux / OSX下使用opendir / readdir / closedir函数。
GLib是一个用于C语言的可移植性/实用性库,是GTK+图形工具包的基础。它可以作为独立库使用。
它包含了管理目录的可移植封装。有关详细信息,请参阅Glib文件实用程序文档。
就个人而言,如果没有像GLib这样的东西支持我,我甚至不会考虑编写大量的C代码。可移植性是一方面,但免费获取数据结构、线程助手、事件、主循环等内容也很好。
哎呀,我几乎开始像销售人员了 :)(别担心,glib是开源的(LGPL),我与之无任何关联)
您可以在Wikibooks链接上找到示例代码。
/**************************************************************
* A simpler and shorter implementation of ls(1)
* ls(1) is very similar to the DIR command on DOS and Windows.
**************************************************************/
#include <stdio.h>
#include <dirent.h>
int listdir(const char *path)
{
struct dirent *entry;
DIR *dp;
dp = opendir(path);
if (dp == NULL)
{
perror("opendir");
return -1;
}
while((entry = readdir(dp)))
puts(entry->d_name);
closedir(dp);
return 0;
}
int main(int argc, char **argv) {
int counter = 1;
if (argc == 1)
listdir(".");
while (++counter <= argc) {
printf("\nListing %s...\n", argv[counter-1]);
listdir(argv[counter-1]);
}
return 0;
}
error: unknown type name 'off64_t'
。 - Tomáš Zatowhile
条件更改为(ep = readdir(dp)) != NULL)
。 - jds