2012-09-17 39 views
3
std::wstring inxmpath (L"folder"); 
HANDLE hFind; 
BOOL bContinue = TRUE; 
WIN32_FIND_DATA data; 
hFind = FindFirstFile(inxmpath.c_str(), &data); 
// If we have no error, loop through the files in this dir 
int counter = 0; 
while (hFind && bContinue) { 
     std::wstring filename(data.cFileName); 
     std::string fullpath = "folder/"; 
     fullpath += (const char*)filename.c_str(); 
     if(remove(fullpath.c_str())!=0) return error; 
    bContinue = FindNextFile(hFind, &data); 
    counter++; 
} 
FindClose(hFind); // Free the dir 

我不明白爲什麼它不起作用,我認爲它與wstring和string之間的轉換有關,但我不確定這一點。我有一個文件夾,它有一些.txt文件,我需要使用C++將它們全部刪除。沒有文件夾在裏面什麼都沒有。這有多難?爲什麼這種刪除文件夾內文件的方法工作?

+0

你試過設置'inxmpath'到一個絕對的文件夾路徑? –

+0

.exe和「文件夾」位於相同的文件夾中。如果情況屬實,我不確定是否需要這樣做。 – ksm001

+1

「不起作用」沒有幫助。你在觀察什麼,你期望什麼,你已經試圖解決它? – tenfour

回答

2

其次,根據MSDN有關FindFirstFile功能:

「搜索文件或子目錄與名稱 特定的名稱(或者如果使用通配符部分名稱)相匹配的一個目錄。」

我在輸入字符串中看不到通配符,所以我只能猜測FindFirstFile將在當前執行目錄中查找名爲"folder"的文件。

嘗試尋找"folder\\*"

+1

我會補充說'FindFirstFile'返回'INVALID_HANDLE_VALUE'錯誤,而不是0像OP期望的那樣。 – tenfour

0

2個問題,我可以看到:

1)我會堅持只寬字符串,如果這就是你所需要的。嘗試改爲調用DeleteFile(假設您的項目是UNICODE),您可以傳遞一個寬字符串。

2)您正在使用相對路徑,其中絕對路徑更健壯。

0

試試這個:

std::wstring inxmpath = L"c:\\path to\\folder\\"; 
std::wstring fullpath = inxmpath + L"*.*"; 

WIN32_FIND_DATA data; 
HANDLE hFind = FindFirstFileW(fullpath.c_str(), &data); 
if (hFind != INVALID_HANDLE_VALUE) 
{ 
    // If we have no error, loop through the files in this dir 
    BOOL bContinue = TRUE; 
    int counter = 0; 
    do 
    { 
     if ((data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) 
     { 
      fullpath = inxmpath + data.cFileName; 
      if (!DeleteFileW(fullpath.c_str())) 
      { 
       FindClose(hFind); 
       return error; 
      } 
      ++counter; 
      bContinue = FindNextFile(hFind, &data); 
     } 
    } 
    while (bContinue); 
    FindClose(hFind); // Free the dir 
} 
相關問題