如何在C目录中扫描文件夹和文件? 它必须是跨平台的。
以下POSIX程序将打印当前目录中的文件名:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| #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))
puts (ep->d_name);
(void) closedir (dp);
}
else
perror ("Couldn't open the directory");
return 0;
} |
图片来源:http://www.gnu.org/software/libtool/manual/libc/Simple-Directory-Lister.html
在Ubuntu 16.04中测试。
严格的答案是"您不能",因为文件夹的概念并不是真正的跨平台。
在MS平台上,您可以使用_findfirst,_findnext和_findclose以获得" c"的感觉,并使用FindFirstFile和FindNextFile进行基础的Win32调用。
这是C-FAQ答案:
http://c-faq.com/osdep/readdir.html
我创建了一个开源(BSD)C头文件来处理此问题。目前,它支持POSIX和Windows。请检查一下:
https://github.com/cxong/tinydir
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| 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("
");
tinydir_next(&dir);
}
tinydir_close(&dir); |
没有标准的C(或C ++)方式枚举目录中的文件。
在Windows下,您可以使用FindFirstFile / FindNextFile函数枚举目录中的所有条目。在Linux / OSX下,使用opendir / readdir / closedir函数。
GLib是C的可移植性/实用性库,它构成了GTK +图形工具箱的基础。它可以用作独立库。
它包含用于管理目录的便携式包装器。有关详细信息,请参见Glib文件实用程序文档。
就个人而言,如果没有像GLib这样的东西,我什至不会考虑编写大量的C代码。可移植性是一回事,但免费获得数据结构,线程助手,事件,主循环等也很不错
吉克斯,我几乎开始听起来像个销售人员:)(不用担心,glib是开源的(LGPL),并且我与它没有任何关系)
opendir / readdir是POSIX。如果POSIX不足以实现您想要的可移植性,请检查Apache Portable Runtime
目录列表根据所考虑的OS /平台而有很大差异。这是因为,各种操作系统使用自己的内部系统调用来实现此目的。
解决此问题的方法是寻找一种掩盖此问题且可移植的库。不幸的是,没有一种可以完美地在所有平台上运行的解决方案。
在兼容POSIX的系统上,您可以使用该库通过Clayton发布的代码来实现此目的(该代码最初是W. Richard Stevens从UNIX下的Advanced Programming中引用的)。如果安装了Cygwin,则此解决方案将在* NIX系统下运行,并且也将在Windows上运行。
或者,您可以编写代码来检测基础操作系统,然后调用适当的目录列表功能,该功能将保持该操作系统下列出目录结构的"正确"方式。
与readdir最相似的方法可能是使用鲜为人知的_find系列函数。
您可以在Wikibooks链接上找到示例代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| /**************************************************************
* 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("
Listing %s...
", argv[counter-1]);
listdir(argv[counter-1]);
}
return 0;
} |