[英]Pointer confusion - c++
我的任務是對 C++ 應用程序進行簡單的更改。 不幸的是,我來自 Java 背景,並且遇到了一些指針問題。
有問題的代碼從給定目錄讀取文件列表(使用環境變量設置),並對每個文件執行一些操作。
char * rebuildDir = getenv("REBUILD_DIR");
char * currentFile;
DIR *asciiDir;
struct dirent *ent;
asciiDir = opendir(rebuildDir);
if (asciiDir != NULL)
{
while ((ent = readdir(asciiDir)) != NULL)
{
std::cout << "rebuild sensor, rebuild dir is " << getenv("REBUILD_DIR") << std::endl;
currentFile = rebuildDir;
strcat(currentFile, ent->d_name);
ifstream raw(currentFile);
while(raw)
{
...snip...
}
raw.close();
}
closedir(asciiDir);
}
可以看到,目的是將環境變量存儲一次,然后將其復制到currentFile,然后將當前文件名連接到currentFile,准備傳入ifstream。
問題是
currentFile = rebuildDir;
不會重置為環境變量,因此 strcat 繼續使用舊文件名並附加到它,所以:
/home/file1
/home/file2
/home/file3
將執行為
/home/file1
/home/file1/home/file2
/home/file1/home/file2/home/file3
通過循環。 我猜我的指針犯了一個基本錯誤,但我無法追蹤它。
感謝您的幫助,並為這個瑣碎的問題道歉。
PS - 如果有明顯更好的方法來完成我的任務,請隨時指出:)
當前文件指向與rebuilddir 相同的memory,因此您可以就地修改字符串。 您需要復制字符串。 您可以執行以下操作:
char currentFile[MAX_PATH];
snprintf(currentFile, MAX_PATH, "%s%s", rebuildDir, ent->d.name);
“...不會重置為環境變量”。 為什么它會“重置”到任何東西? 您將指針currentFile
指向rebuildDir
指向的實際環境變量值。 然后您通過strcat
修改指針,即您實質上是在修改(即破壞)您的原始環境變量值。
你不應該那樣做。 如果要從環境變量的值構建新名稱,則必須將該值復制到一邊,然后修改副本,而不是試圖破壞原始值。
例如,您可以使用std::string
在原始值上創建副本
const char *rebuildDir = getenv("REBUILD_DIR");
...
std::string currentFile = rebuildDir;
currentFile += ent->d_name;
ifstream raw(currentFile.c_str());
int main(int argc, char *argv[])
{
char* pDir = getenv("REBUILD_DIR");
if (! pDir)
{
cerr << "did not find ENV var\n";
exit(1);
}
string rebuildDir(pDir);
DIR* asciiDir;
if ((asciiDir = opendir(rebuildDir.c_str())) != NULL)
{
std::cout << "rebuild sensor, rebuild dir is " << rebuildDir << std::endl;
struct dirent *ent;
while ((ent = readdir(asciiDir)) != NULL)
{
string currentFile(rebuildDir);
currentFile += '/' + string(ent->d_name);
//probably want to skip "." and ".." entries...
/*
ifstream raw(currentFile);
while(raw)
{
...snip...
}
raw.close();
*/
}
closedir(asciiDir);
}
else
{
cerr << "coult not open dir\n";
exit(1);
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.