我一直负责对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