gpt4 book ai didi

c++ - 如何将 char 复制到 char* vector 中

转载 作者:太空狗 更新时间:2023-10-29 23:29:59 25 4
gpt4 key购买 nike

我正在使用 dirent 从特定文件夹中读取文件名,我想将名称保存在 char* vector 中。它似乎在复制一些奇怪的符号而不是复制文件名。到目前为止,这是我尝试过的:

std::vector<char*> filenames;

int filenamesAndNumberOfFiles(char *dir)
{
struct dirent *dp;
DIR *fd;
int count = 0;

if ((fd = opendir(dir)) == NULL)
{
fprintf(stderr, "listdir: can't open %s\n", dir);
return 0;
}
while ((dp = readdir(fd)) != NULL)
{
if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
continue; /* skip self and parent */
printf("Filename: %s\n", dp->d_name);
filenames.push_back(dp->d_name);
count++;
}
closedir(fd);
return count;
}

谁能告诉我为什么它不复制文件名,我该怎么做才能复制它们?

编辑:d_name 是一个 char 变量,声明为:

char d_name[PATH_MAX];

在我的程序中,PATH_MAX 似乎等于 260。

PS:第一次用dirent,不是很熟悉。

最佳答案

替换std::vector<char*>std::vector<std::string> .并添加 #include <string> .这应该可以解决问题。

您似乎还没有掌握 C/C++ 中指针和数组的概念,我不确定解释这些是否符合 SO 答案的范围。但是这个答案可能有用:C++ : Does char pointer to std::string conversion copy the content?

简而言之,您的代码的问题在于,您没有复制存储字符串的内存(字符本身,char[PATH_MAX]),而是只复制指向该内存的指针(char*)。并且指向的内存块后来被重用甚至删除,导致你存储的指针无效。

关于c++ - 如何将 char 复制到 char* vector 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34762800/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com