获取给定目录及其子目录中所有文件的路径和文件名
不久前我得到了这个代码。 我终于开始测试它(进行一些更改以将文件放在不同的位置)......
void AddFiles(AnsiString path/*, TDataSet *DataSet*/)
{
TSearchRec sr;
int f;
f = FindFirst(path+"\\*.*", faAnyFile, sr);
while( !f )
{
if(sr.Attr & faDirectory)
{
if(sr.Name != "." && sr.Name != "..")
{
path.sprintf("%s%s%s", path, "\\", sr.Name);
AddFiles(path/*, DataSet*/);
}
}
else
{
Form1->ListBox1->Items->Add(path+ "\\"+ sr.Name);
//DataSet->Append();
//DataSet->FieldByName("Name")->Value = sr.Name;
/* other fields ... */
//DataSet->Post();
}
f = FindNext(sr);
}
FindClose(sr);
}
它无法正常工作。 一开始它就变得混乱了……
的真实结构
根 根\子目录1 根\子目录2 root\subdir3
变得像这样混乱......
root 根目录\子目录1 根\子目录1\子目录2 root\subdir1\subdir2\subdir3
并最终停止包含根或 sub\sub 文件夹,并且“路径”仅包含一个子文件夹(没有其根文件夹),
这对于获取可用的完整路径文件名完全没有用。
所以或者你能告诉我代码哪里出了问题吗...或者给我一些关于如何获取目录及其所有子目录中的完整路径文件名的建议。
我希望它尽可能基本。 即没有不常见的高级 C++ 功能。 构建者菜鸟可能能够调试的东西。
I was given this code a while back. I finally got around to testing it (with some changes to put the files in a different place)...
void AddFiles(AnsiString path/*, TDataSet *DataSet*/)
{
TSearchRec sr;
int f;
f = FindFirst(path+"\\*.*", faAnyFile, sr);
while( !f )
{
if(sr.Attr & faDirectory)
{
if(sr.Name != "." && sr.Name != "..")
{
path.sprintf("%s%s%s", path, "\\", sr.Name);
AddFiles(path/*, DataSet*/);
}
}
else
{
Form1->ListBox1->Items->Add(path+ "\\"+ sr.Name);
//DataSet->Append();
//DataSet->FieldByName("Name")->Value = sr.Name;
/* other fields ... */
//DataSet->Post();
}
f = FindNext(sr);
}
FindClose(sr);
}
It doesn't work properly. In the beginning it gets mixed up..
a real structure of...
root
root\subdir1
root\subdir2
root\subdir3
gets messed up like this...
root
root\subdir1
root\subdir1\subdir2
root\subdir1\subdir2\subdir3
and eventually it stops including the root or sub\sub folders and 'path' just contains a subfolder (without its root folders)
this is completely useless for aquring useable full-path filenames.
so either can you tell me where the code is going wrong... or give me some advice on how to get the full path filenames in a dir and all its subdirs.
I want it to be as basic as possible. i.e. no uncommon advanced c++ features. stuff that a builder noob is likely to be able to debug.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在这里,您将每个子路径附加到当前路径:
对组合路径使用新变量,这样您就不会弄乱目录中其余文件/目录仍然需要的
path
变量:Here you append each subpath to the current path:
Use a new variable for the combined path, so you don't mess up the
path
variable you still need for the rest of the files/dirs in the directory: