[英]Intel C Compiler unable to use standard libs (e.g. dirent.h) on Linux
[英]C use of dirent.h
最终更新 -答案在接受答案的注释中。
首先,我意识到这个问题还有很多其他答案。 我经历了其中的大多数,并且此代码是经历许多其他答案的组合。 我要做的就是获取目录中每个文件的完整路径。
#include <limits.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
DIR *d;
struct dirent * dir;
char fullpath[PATH_MAX + 1];
d = opendir("/home/adirectory");
if(d != NULL)
{
while((dir = readdir(d)) != NULL)
{
realpath(dir->d_name, fullpath);
printf("[%s]\n", fullpath);
printf("%s\n", dir->d_name);
}
// addition of the following line yields
// Value too large for defined data type
perror("Something isn't working: ");
closedir(d);
}
return 0;
}
更新#3:
失败的调用是dir = readdir(d)
,这就是为什么while循环后立即出现错误的原因。
更新#2:
这在CentOS和Ubuntu gcc 4.8.5 +上可以正常工作。 在Solaris gcc 4.5.2上不起作用。
更新:有错误消息:
值对于定义的数据类型而言太大
...但是我不确定是什么原因造成的。
这总是只打印我正在从中运行程序的当前工作目录。 即使这样,它实际上也不会列出该目录中除“”之外的任何文件。 和“ ..”。 是什么赋予了? 是否存在某种许可问题? 此解决方案在2017年不起作用吗?
d_name
字段在其遍历目录的上下文中包含文件的名称。 因此,它不包含任何路径,仅包含名称。
因此,为了让您使用其路径,您需要将d_name
附加到目录名称中,如下所示:
char *myHomeDir = "/home/adirectory";
d = opendir(myNomDir);
. . .
while((dir = readdir(d)) != NULL) {
char filepath[PATH_MAX + 1] ;
strcpy(filepath, myHomeDir);
strcat(filepath, "/");
strcat(filepath, dir->d_name);
realpath(filepath, fullpath);
当然,为了清楚起见,上面的内容只是一个基本代码。 可以对其进行更好的优化,您应该使用strncpy
系列函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.