我一直負責對C++應用程序進行簡單的更改。不幸的是,我來自Java背景,並且遇到了一些指針問題。指針混淆 - C++
有問題的代碼讀取來自給定目錄(使用環境變量設置)的文件列表,並對每個文件執行一些操作。
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,然後concatonate當前文件名currentFile,準備進入ifstream的。
的問題是,
currentFile = rebuildDir;
沒有重置環境變量,所以strcat的不斷使用舊的文件名,並追加到它,所以:
/home/file1
/home/file2
/home/file3
將執行作爲
/home/file1
/home/file1/home/file2
/home/file1/home/file2/home/file3
通過循環。我在猜測我用指針犯了一個元錯誤,但我一直沒有找到它。
感謝您的任何幫助,併爲微不足道的問題道歉。
PS - 如果有一個明顯更好的方法來完成我的任務,請你這樣的修改字符串中的地方隨時指出來:)
感謝您的答案每個人,都非常有用。 – Caligari 2011-05-25 03:27:27