tpa*_*r44 2 c unix linux filesystems traversal
我有一个问题fts(3).每当我尝试访问该fts_children()函数的任何成员时,我都会遇到分段错误.当我阅读http://www.kernel.org/doc/man-pages/online/pages/man3/fts.3.html上的手册页时,它声称在读取函数运行后填充自己并返回链接的链接列表通过link结构领域.我的怀疑是child_function没有返回任何内容,但我觉得这不符合手册页.我应该将这些文件添加到子缓冲区,因为我认为这是自动完成的吗?我的代码在下面,谢谢!
#include<stdlib.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fts.h>
#include<string.h>
int compare (const FTSENT**, const FTSENT**);
int main(int argc, char* const argv[])
{
FTS* file_system = NULL;
FTSENT* child = NULL;
FTSENT* parent = NULL;
FTSENT* temp = NULL;
file_system = fts_open(argv + 1,FTS_COMFOLLOW | FTS_NOCHDIR,&compare);
while( (parent = fts_read(file_system)) != NULL)
{
child = fts_children(file_system,0);
printf("%s\n", child->fts_path);
}
// while (child ->fts_link != NULL)
// child = child->fts_link;
fts_close(file_system);
return 0;
}
int compare(const FTSENT** one, const FTSENT** two){
return (strcmp((*one)->fts_name, (*two)->fts_name));
}
"test_fs.c" 43L, 1108C
Run Code Online (Sandbox Code Playgroud)
如果您只对遍历指定路径的所有目录和文件感兴趣,请重复调用fts_read.
如果您只想遍历流,@ sehe的示例可以重写为:
#include<stdlib.h>
#include<stdio.h>
#include<sys/types.h>
#include<fts.h>
#include<string.h>
#include<errno.h>
int compare (const FTSENT**, const FTSENT**);
void indent (int i);
int main(int argc, char* const argv[])
{
FTS* file_system = NULL;
FTSENT *node, = NULL;
if (argc<2)
{
printf("Usage: %s <path-spec>\n", argv[0]);
exit(255);
}
file_system = fts_open(argv + 1,FTS_COMFOLLOW|FTS_NOCHDIR,&compare);
if (NULL != file_system)
{
while( (node = fts_read(file_system)) != NULL)
{
switch (node->fts_info)
{
case FTS_D :
case FTS_F :
case FTS_SL:
indent(node->fts_level);
printf("%s\n", node->fts_name);
break;
default:
break;
}
}
fts_close(file_system);
}
return 0;
}
int compare(const FTSENT** one, const FTSENT** two)
{
return (strcmp((*one)->fts_name, (*two)->fts_name));
}
void indent(int i)
{
for (; i > 0; i--)
printf(" ");
}
Run Code Online (Sandbox Code Playgroud)
当您运行它时,它会遍历流并按顺序列出所有文件和目录:
? mkdir -p test/A/1 test/A/2 test/B/1 test/B/2
? tree test
test
??? A
? ??? 1
? ??? 2
??? B
??? 1
??? 2
? ./fts test
test
A
1
2
B
1
2
Run Code Online (Sandbox Code Playgroud)
fts_children仅在需要特定目录的子节点列表时调用.在这种情况下,你必须fts_read至少打电话一次才能打电话fts_children; 否则fts_children 只会返回argv参数中指定的节点fts_open.
| 归档时间: |
|
| 查看次数: |
6050 次 |
| 最近记录: |