我被分配任务对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 - 如果有更好的方法来完成我的任务,请随时指出 :)
snprintf
(即使MAX_PATH
“相当大”)。 - aschepler[v][sf][n]printf
的习惯,而是使用std::string
:std::string currentFile(rebuildDir); currentFile += ent->d.name;
- Serge Dundich