1

假设我在文件夹 c:/ 中有 3 个扩展名为“.exe”的文件。我想创建 3 个 char* 类型的指针,每个指针都包含 .exe 文件的文件名。所以,我们有 3 个指针 - 3 个文件名。但真正让我感到困惑的是输出(见下文)。

我的实现:

#include <dirent.h>

// some code here

DIR *dir;
struct dirent *ent;
char** FileName = new char* [3]; // Creating 3 pointers of type char*
count = 0; //counting the events when .exe file detected
dir = opendir("c:/");
while ((ent = readdir (dir)) != NULL) // read directory file by file until there is nothing
      {
            string matchName = string(ent->d_name);
            if (matchName.find(".exe") != std::string::npos) // Finding files with 
                                                             //.exe extension only
            {
               FileName[count] = ent->d_name;
               cout << "count = " << count << ": " << FileName[count] << endl;
               count++; // There are 3 .exe files in the folder, so the maximum
                        // of the count=3 (from FileName[0] to FileName[2])
            }
      }
closedir (dir);

// Here I'm just checking the output
cout << "count = 0: " << FileName[0] << endl;
cout << "count = 1: " << FileName[1] << endl;
cout << "count = 2: " << FileName[2] << endl;

我的输出:

//from inside the while-loop:
count = 0: file0.exe
count = 1: file1.exe
count = 2: file2.exe

//from when I just check the output outside the loop        
count = 0:  // just empty for all 3 files
count = 1: 
count = 2:

为什么我在 while 循环内时有预期的赋值(至少是预期的),但是当我检查循环外指针的相同值时 - 它只是空的?谢谢!

4

2 回答 2

2

这是个问题:

FileName[count] = ent->d_name;

每次调用都readdir可能返回相同的ent,只是现在它指向的值不同。您应该从中复制字符串,而不是指向此临时存储区域。

最简单的方法是更改FileName​​为:

std::string FileName[3];

尽管正确使用不会花费太多精力std::vector<std::string> FileName;,但是您没有3个文件的限制。

于 2014-05-20T23:00:02.187 回答
1

也许你的数据被覆盖了?引用 readdir 帮助: The data returned by readdir() may be overwritten by subsequent calls to readdir() for the same directory stream。因此,您应该复制 char 数组而不是分配原始 char 指针

于 2014-05-20T22:59:04.203 回答