将值赋给while-loop内部的指针(使用< direct .h>)
Assignment of the values to the pointers inside while-loop (using <dirent.h>)
假设我在文件夹c:/中有3个扩展名为".exe"的文件。我想创建3个char*类型的指针,每个指针都包含。exe文件的文件名。我们有3个指针,3个文件名。但真正让我困惑的是输出(见下文)。
我实现:#include <dirent.h>
// some code here
DIR *dir;
struct dirent *ent;
char** FileName = new char* [3]; // Creating 3 pointers of type char*
count = 0; //counting the events when .exe file detected
dir = opendir("c:/");
while ((ent = readdir (dir)) != NULL) // read directory file by file until there is nothing
{
string matchName = string(ent->d_name);
if (matchName.find(".exe") != std::string::npos) // Finding files with
//.exe extension only
{
FileName[count] = ent->d_name;
cout << "count = " << count << ": " << FileName[count] << endl;
count++; // There are 3 .exe files in the folder, so the maximum
// of the count=3 (from FileName[0] to FileName[2])
}
}
closedir (dir);
// Here I'm just checking the output
cout << "count = 0: " << FileName[0] << endl;
cout << "count = 1: " << FileName[1] << endl;
cout << "count = 2: " << FileName[2] << endl;
我输出://from inside the while-loop:
count = 0: file0.exe
count = 1: file1.exe
count = 2: file2.exe
//from when I just check the output outside the loop
count = 0: // just empty for all 3 files
count = 1:
count = 2:
为什么我期望赋值(至少,期望)当我在while-loop内,但当我检查循环外的指针的相同值-它只是空的?谢谢你!
这是一个问题:
FileName[count] = ent->d_name;
每次调用readdir
都可能返回相同的ent
,只是现在它指向的位置有不同的值。你应该把字符串复制出来,而不是指向这个临时存储区域。
最简单的方法是将FileName
更改为:
std::string FileName[3];
虽然正确使用std::vector<std::string> FileName;
不会花费更多的精力,但是您不需要限制3个文件。
也许你的数据被覆盖了?引用自readdir帮助:The data returned by readdir() may be overwritten by subsequent calls to readdir() for the same directory stream
。所以,你应该复制char数组而不是赋值原始char指针
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- C++:TypeDef使用元组
- 使用std::multimap迭代器创建std::list
- 从不同线程使用int64的不同字节安全吗
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么在全局范围内使用"extern int a"似乎不行?
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用Google Mock来模拟gettimeofday()
- 如何使用默认参数等选择模板专业化
- 使用 c++/WinRT Direct3D UWP Game DR 模板 Direct X11 的错误消息
- DirectX 11 2D游戏引擎使用Direct 3D(C )
- 在Visual Studio 2013中使用旧的Direct X SDK
- 为什么使用 Direct X 链接会大大增加我的程序大小
- Direct X使用C++,当我在FX文件中找到一种技术时,我收到了一个访问违规
- 运行时检查失败 #3 - 变量'direct'正在使用未初始化
- 如果QObject是从direct派生的,那么使用“虚拟”多重继承是否安全?
- 在使用Direct 3D时,哪些应该在代码中处理,哪些应该在HLSL中处理
- 将值赋给while-loop内部的指针(使用< direct .h>)
- 使用Media Foundation对Direct X曲面进行编码