[英]Extracting a file name from the path
好吧,我有以下內容:
wchar_t **filePathList;
它包含要添加到列表框中的文件的列表。 問題在於它們顯示了整個文件路徑,而我只想獲取名稱。 我考慮過使用:
wchar_t *tempChar;
從filePathList的末尾開始,然后回溯到\\
。 問題是我不確定如何管理。 這是到目前為止我得到的代碼:
afx_msg void Send::OnDropFiles(HDROP hDropInfo)
{
if(uploadInProgress)
{
MessageBox(L"Please wait for current upload to finish before adding files", L"Upload in progress", MB_OK);
return;
}
int len;
int prevNFiles = nFiles;
wchar_t **buffer = filePathList;
wchar_t *tempChar = NULL;
// get number of files dropped into window
nFiles += DragQueryFile(hDropInfo, 0xFFFFFFFF, NULL, 0);
filePathList = (wchar_t**)malloc(nFiles*sizeof(wchar_t*));
if(!filePathList)
{
MessageBox(L"FilePath list memory allocation failed", L"Error");
nFiles = 0;
if(buffer)
{
for(int i=0; i<prevNFiles; i++)
{
if(buffer[i]) free(buffer[i]);
}
free(buffer);
}
return;
}
memset(filePathList, 0, nFiles*sizeof(wchar_t*));
// get file names
for(int i=0; i<nFiles; i++)
{
if(i < prevNFiles)
{ // previously entered files
filePathList[i] = buffer[i];
continue;
}
// newly dropped files
len = DragQueryFile(hDropInfo, i-prevNFiles, NULL, 0)+1; // 1 for \0
tempChar = (wchar_t*)malloc(len*sizeof(wchar_t));
filePathList[i] = (wchar_t*)malloc(len*sizeof(wchar_t));
int index = len;
// Attempting to iterate through the path to get the file name
while(filePathList[i][index] != '\\')
{
tempChar = filePathList[index];
index--;
}
filePathList[i] = tempChar;
if(!filePathList[i])
{
MessageBox(L"FilePath memory allocation failed", L"Error");
for(int j=0; j<i; j++)
{
if(filePathList[j]) free(filePathList[j]);
}
free(filePathList); filePathList = NULL;
nFiles = 0;
break;
}
len = DragQueryFile(hDropInfo, i-prevNFiles, filePathList[i], len);
}
if(buffer) free(buffer);
// display files
UpdateFileListDisplay();
}
問題是Visual Studio將tempChar報告為“錯誤的ptr”。 我承認在編程方面我還是很環保,對指針了解甚少,而對雙指針則了解甚少。 但任何幫助將不勝感激。 謝謝。
您正在使用的函數的編寫長度為76行。 那不是災難性的長,但是到了很難推理的地步。 將這個功能分成幾個較小的功能可能是值得的。 您正在處理的一個問題是如何從完整路徑提取文件名。 您可以編寫一個簽名如下的函數:
char *filename_from_path(const char *fullpath);
它采用完整路徑並返回僅包含文件名的新字符串。 (注意:您必須注意誰分配和釋放文件名字符串)。 分解這樣一個函數的整潔之處在於,通常有關於如何做這些小片段的好建議:
例如, 使用MSVS2005從C中的完整路徑提取文件名 。
分離出該邏輯將使您更容易推斷正在處理的較大循環。
錯誤在以下代碼中:
tempChar = (wchar_t*)malloc(len*sizeof(wchar_t));
filePathList[i] = (wchar_t*)malloc(len*sizeof(wchar_t));
int index = len;
// Attempting to iterate through the path to get the file name
while(filePathList[i][index] != '\\')
{
tempChar = filePathList[index];
index--;
}
這里有幾個問題:
len
不包含空終止符,因此您沒有分配足夠的內存。 您還需要一個角色。 DragQueryFile
來填充緩沖區。 filePathList[i][index]
首次訪問超出了范圍,因為index
超出了數組的末尾。 filePathList[i]
因此循環可能會遞減至index
0,然后產生訪問沖突。 index>=0
,以防字符串不包含路徑分隔符。 我沒有看過您問題中的任何其他代碼,但我敢打賭我沒有找到所有錯誤。 現在應該足夠了。
Joachim關於使用_splitpath
的建議非常合理,但在另一方面,您確實需要掌握這種編碼。
您也可以打開文件以找到其名稱。 盡管那可能和走這條路一樣慢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.