2014-05-20 30 views
1

假設我在文件夾c:/中有3個帶有擴展名爲「.exe」的文件。 我想創建3個類型爲char *的指針,每個指針都包含.exe文件的文件名。所以,我們有3個指針 - 3個文件名。 但輸出是真正混淆了我(見下文)。將值分配給while循環內部的指針(使用<dirent.h>)

我的實現:

#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循環裏面,但是當我檢查循環外部指針的相同值 - 它只是空的? 謝謝!

回答

2

這個字符數組是一個問題:

FileName[count] = ent->d_name; 

readdir每次調用可能返回相同的ent,只是有不同的值,現在它在哪裏指點。您應該將字符串複製出來,而不是指向這個臨時存儲區域。

要做到這一點最簡單的方法是改變FileName到:

std::string FileName[3]; 

雖然這將是正確使用std::vector<std::string> FileName;沒有更多的努力,那麼你沒有你的3個文件的限制。

+0

謝謝!這解決了這個問題 – chetmik

1

也許你的數據被覆蓋?從readdir幫助引用: The data returned by readdir() may be overwritten by subsequent calls to readdir() for the same directory stream。 所以,你應該複製而不是分配原始字符指針

+0

謝謝!我確實在所有情況下只使用了一個指針 - 因此它每次都會覆蓋 – chetmik