如何使用 C++ 获取路径的文件和目录列表?

发布于 2024-10-21 16:02:56 字数 808 浏览 1 评论 0原文

我正在使用目录类来获取此信息,但无法将此数据分配给我自己的类的数据成员。我正在做一个 oop 项目。此外,我想使用动态(包含)的概念。我创建了两个类,mydirectory 和 myfiles,如下所示:

class files
{
    string fname[25];
public:
    files()
    {
      fname=NULL;
    }

};

class directory
{ private:
    directory *d;
    string *dname[25];   //* to show there may be a subdirectory,there may be not.
    files *ff[25];       // data member string *fname[25];
int numd,numf;
public:
    directory()
    {
    numd=0;numf=0;
    }

现在,如果我想使用语句:

 Directory::GetDirectories("D:\\"); 

how can I allocate thedirectory name to "dname" of directory class 。

我不想包含第三方软件。

我还需要有关以下主题的帮助:如何从控制台外部的 C++ 代码打开文件(doc 文件/pdf/txt/pwt 等)?我很担心。请帮我。提前致谢。

我是 C++ 新手,所以如果指针处理中有任何错误,请原谅,因为我是第一次进行这种遏制。我还需要一些阅读材料。

I am using the directory class to get this information but unable to assign this data to a data member of my own class. i am doing an oop project. Furthermore,I want to use the concept of Dynamism(containment).I have created two class, mydirectory and myfiles as under:

class files
{
    string fname[25];
public:
    files()
    {
      fname=NULL;
    }

};

class directory
{ private:
    directory *d;
    string *dname[25];   //* to show there may be a subdirectory,there may be not.
    files *ff[25];       // data member string *fname[25];
int numd,numf;
public:
    directory()
    {
    numd=0;numf=0;
    }

Now when if I want to use the statment:

 Directory::GetDirectories("D:\\"); 

how can I assign the directory names to "dname" of directory class.

I dont want to include a third party software.

also i need help on the topic: how can a file (doc file/pdf/txt/pwt etc) can be opened from c++ code outside the console? I am very worried. please help me. thanks in advance.

I am new to c++ so please forgive if there are any errors in pointer handling, as I am doing this containment for the first time. I also need some reading stuff.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

魂牵梦绕锁你心扉 2024-10-28 16:02:56

在 C++ 中最简单的方法是使用 boost::filesystem。

只要路径是目录,您就可以使用 Directory_iterator 或 recursive_directory_iterator 对其进行迭代。

例如:

boost::filesystem::path dirname( "D:\\" );

std::vector<boost::filesystem::path> topLevel( directory_iterator(dirName), 
      directory_iterator() );

std::vector<boost::filesystem::path> wholeDrive( 
       recursive_directory_iterator(dirName), recursive_directory_iterator() );

The simplest way to do it in C++ is using boost::filesystem.

As long as the path is a directory you can iterate over it using either a directory_iterator or a recursive_directory_iterator.

eg:

boost::filesystem::path dirname( "D:\\" );

std::vector<boost::filesystem::path> topLevel( directory_iterator(dirName), 
      directory_iterator() );

std::vector<boost::filesystem::path> wholeDrive( 
       recursive_directory_iterator(dirName), recursive_directory_iterator() );
乜一 2024-10-28 16:02:56

由于这是已标记的家庭作业,因此我们不会为您提供正确答案,从而为您提供太多帮助。但我会为你指出正确的方向。

您已表明您是在 Visual C++ 下执行此操作。如果不使用任何第三方库而仅使用内置库,您将需要访问 Win32 API。

查找第一个文件() & FindNextFile() 就是您所需要的。

您将首先调用 FindFirstFile 来获取目录句柄。
该参数是您传递到类中的 D:\。

然后在 while 循环中调用 FindNextFile。

例如,使用这些 API 的基本原则是

HANDLE h = FindFirstFile("D:\\");
WIN32_FIND_DATA data;
while (FindNextFile(h, &data))
{
   // Check if it's a directory or not
   if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY){
     // Add to dname
   }
}

考虑使用 std::vector 作为你的 dname 而不是 string*
因为你被 25 个条目困住了。使用矢量它会为你成长。

As this is marked homework, we're not going to be helping you much by giving you the correct answer. But I will point you in the right direction.

You've indicated you're doing this under Visual C++. Well without using any third party libraries but just what's built in, you'll need to access the Win32 API.

FindFirstFile() & FindNextFile() are what you need.

You'll call FindFirstFile first off to obtain the directory handle.
The parameter is the D:\ that you're passing into your class.

Then call FindNextFile in a while loop.

e.g. The basic principle of using those API's is

HANDLE h = FindFirstFile("D:\\");
WIN32_FIND_DATA data;
while (FindNextFile(h, &data))
{
   // Check if it's a directory or not
   if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY){
     // Add to dname
   }
}

Consider using std::vector for your dname instead of string*
because you're stuck with 25 entries. Using vector it'll grow for you.

北笙凉宸 2024-10-28 16:02:56

正如 CashCow 所说, boost::filesystem

作为一般规则,在 C++ 中,对于此类示例,您不需要任何指针。这里有一些你应该纠正的错误:

string fname[25];

这声明了一个包含 25 个字符串的数组。您可能想要一个 25 个字符的字符串?好吧,在 std::string 中,您不需要关心长度。 std::字符串 fname;就足够了

std::string file_name;
file_name = "baz.txt";

fname=NULL;

如果fname是一个字符串,那么它就不是一个指针。所以你不能给它分配NULL。 std::string 默认情况下初始化为空字符串。您可以省略整个构造函数。

string *dname[25]

我想你想要一个字符串数组。只需使用 :

std::vector<std::string> dnames;
dnames.push_back("foo");
dnames.push_back("bar"); // dnames now contains {"foo","bar"}

你就会有一个动态调整大小的字符串向量。

请参阅:不需要任何指针。不需要任何新的

As said CashCow, boost::filesystem

As a general rule, in C++ for such examples, you don't need any pointer. Here a some mistakes you should correct:

string fname[25];

This declares an array of 25 strings. You probably wanted a string of 25 chars ? Well, in std::string, you don't need to care about the length. std::string fname; is enough

std::string file_name;
file_name = "baz.txt";

fname=NULL;

If fname is a string, then it's not a pointer. So you can't assign NULL to it. A std::string is by default initialized as an empty string. You can leave the whole constructor out.

string *dname[25]

I suppose you wanted to have an array of string. Just use :

std::vector<std::string> dnames;
dnames.push_back("foo");
dnames.push_back("bar"); // dnames now contains {"foo","bar"}

And you'll have a dynamically resizable vector of strings.

See : no need of any pointer. No need for any new

入怼 2024-10-28 16:02:56

最后我完成了这个简短的项目。为了获取文件和子目录的列表,我使用了 .NET Framework 命名空间“System”。它具有诸如“FileInfo”之类的类”和“DirectoryInfo”(都属于System::IO),它们执行上述所需的任务。但是在这里,所有与字符串相关的东西都是System的: :String ,而不是 std::string。要将 System::String 转换为 std::string,我使用了以下代码(我从论坛获得了此转换的代码,它工作正常,没有任何错误):

string Str2str(String ^a)
{
array<Byte> ^chars = System::Text::Encoding::ASCII->GetBytes(a);
pin_ptr<Byte> charsPointer = &(chars[0]);
char *nativeCharsPointer = reinterpret_cast<char *>(static_cast<unsigned char *>(charsPointer));
string native(nativeCharsPointer, chars->Length);
return native;
}

这是一个从驱动器获取子目录列表的简短代码(D:将搜索驱动器):

 #include<iostream>
        #using<mscorlib.dll>
        using namespace strd;        
        using namespace System;
        using namespace System::IO;


int main()
    {int count=50;
string name[count];//to hold directories names
string b;
int s=0;
DirectoryInfo^ di = gcnew DirectoryInfo("d:\\");
if(di->Exists)
{array<DirectoryInfo^>^diArr = di->GetDirectories();
Collections::IEnumerator^ myEnum = diArr->GetEnumerator();
while ( myEnum->MoveNext() )
{DirectoryInfo^ dri = safe_cast<DirectoryInfo^>(myEnum->Current);


      String ^a=(dri->Name->ToString());
      int n=b.size();
      b=Str2str(a); `// code given in the starting`
      if (s<count)
      {name[s]=b;
      s++;}

}

这涉及托管 C++ 知识。请访问这些:

.NET 编程指南

C++:最强大的 .NET Framework 编程语言

我在 Visual Studio 上编译了此代码2008年。如果您认可我的努力,我将非常感激。非常欢迎进一步的建议。

Finally I completed the short project.To get the list of files and sub directories, I made use of .NET Framework namespace "System".It has got classes like "FileInfo" and "DirectoryInfo"(both belong to System::IO) which do the above required task.But here,all the string related stuff is of System::String , not of std::string.To convert System::String to std::string, I used the following code(I got this conversion's code from a forum and it worked fine without any error):

string Str2str(String ^a)
{
array<Byte> ^chars = System::Text::Encoding::ASCII->GetBytes(a);
pin_ptr<Byte> charsPointer = &(chars[0]);
char *nativeCharsPointer = reinterpret_cast<char *>(static_cast<unsigned char *>(charsPointer));
string native(nativeCharsPointer, chars->Length);
return native;
}

Here is a short code for getting list of sub directories from a drive(D: drive is going to be searched):

 #include<iostream>
        #using<mscorlib.dll>
        using namespace strd;        
        using namespace System;
        using namespace System::IO;


int main()
    {int count=50;
string name[count];//to hold directories names
string b;
int s=0;
DirectoryInfo^ di = gcnew DirectoryInfo("d:\\");
if(di->Exists)
{array<DirectoryInfo^>^diArr = di->GetDirectories();
Collections::IEnumerator^ myEnum = diArr->GetEnumerator();
while ( myEnum->MoveNext() )
{DirectoryInfo^ dri = safe_cast<DirectoryInfo^>(myEnum->Current);


      String ^a=(dri->Name->ToString());
      int n=b.size();
      b=Str2str(a); `// code given in the starting`
      if (s<count)
      {name[s]=b;
      s++;}

}

This involves Managed C++ knowledge. Visit these:

.NET Programming Guide

C++: The Most Powerful Language for .NET Framework Programming

I compiled this on Visual Studio 2008. I will be very grateful if you appriciate my effort.Further suggestions are most welcomed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文