在 C++ 中使用 cstrings 构建路径的正确方法

发布于 2024-09-26 21:59:41 字数 841 浏览 2 评论 0原文

我需要建立一个文件的路径。我有以下类方法:

void Directory::scanDirectory(char *directory) {
    DIR *dirp;
    struct dirent *entry;
    char path[1];

    if(dirp = opendir(directory)) {
        while(entry = readdir(dirp)) {
            if (entry->d_name[0] != '.') {
                strcpy(path, directory);
                strcat(path, "/");
                strcat(path, entry->d_name);
                if (entry->d_type == 8) {
                    // Files
                } else if (entry->d_type == 4) {
                    //scanDirectory(path);
                }
                printf("Name: %s, Type: %d\n", entry->d_name, entry->d_type);
            }
        }
        closedir(dirp);
    }
}

我需要通过连接目录和 entry->d_name 来构建文件路径。当我尝试运行这段代码时,它出现段错误。据我所知,在我构建路径的地方出现了段错误。有更好的方法吗?

I need to build up a path to a file. I have the following class method:

void Directory::scanDirectory(char *directory) {
    DIR *dirp;
    struct dirent *entry;
    char path[1];

    if(dirp = opendir(directory)) {
        while(entry = readdir(dirp)) {
            if (entry->d_name[0] != '.') {
                strcpy(path, directory);
                strcat(path, "/");
                strcat(path, entry->d_name);
                if (entry->d_type == 8) {
                    // Files
                } else if (entry->d_type == 4) {
                    //scanDirectory(path);
                }
                printf("Name: %s, Type: %d\n", entry->d_name, entry->d_type);
            }
        }
        closedir(dirp);
    }
}

I need to build up the path to files by concatenating the directory and entry->d_name. When I try running this code it segfaults. From what I can tell it's segfaulting at the point where I build the path. Is there a better way of doing this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

迷乱花海 2024-10-03 21:59:41

您仅为路径分配一个字节 (char path[1])。您需要分配足够的空间来实际容纳您正在创建的整个路径。给定 C++ 标记,明显的可能性是使用 std::string,并且在将所有部分组合成完整路径后,使用其 c_str() 成员函数来访问 C 风格字符串的内容。

You're only allocating one byte for the path (char path[1]). You need to allocate enough space to actually hold the whole path you're creating. Given the C++ tag, the obvious possibility would be to use an std::string, and after you've put all the pieces together into a complete path, use its c_str() member function to get access to the contents as a C-style string.

情独悲 2024-10-03 21:59:41

为什么不使用 Boost.Filesystem

Why not use Boost.Filesystem ?

一杯敬自由 2024-10-03 21:59:41

缓冲区path需要有足够的空间来容纳整个路径。现在它只有一个字符的空间。尝试把它做得更大。 strcat 本身不分配空间。您必须手动管理该内存。

至于更好的方法,您可能需要考虑使用字符串。您无需担心内存问题,并且可以使用 + 运算符进行连接。

The buffer path needs to have enough space to hold the whole path. Right now it only has space for a single character. Try making it bigger. strcat doesn't allocate space itself. You have to manually manage that memory.

As for a better way, you may want to look into using a string. You won't need to worry about memory, and you can concatenate with the + operator.

转身以后 2024-10-03 21:59:41

char path[1]; 更改为:

char path[512]; //or whatever value you like.

在您的代码中,path 仅为 1 个字符和 \0 分配了空间。显然你需要一个更大的,据我所知,在unix中,目录名最多可以有255个字符,所以我认为512就足够了。

Change char path[1]; to:

char path[512]; //or whatever value you like.

On your code, path only allocated space for 1 character and \0. You need a bigger one obviously, and as far as I know, in unix, the directory name can be upto 255 characters, so 512 would be enough in my opinion.

一曲爱恨情仇 2024-10-03 21:59:41

使用strcpy时要小心。它不进行边界检查,因此即使 path 只是 char[1],它也会尝试将所有 directory 复制到其中。这可能是你的段错误。

在如何构建字符串方面,您有很多选择。这是一篇关于 C++ 字符串连接效率的长篇文章:

Efficient string concatenation in C++

如果您使用 C++,是否有任何原因不能仅将内置 string 库与 + 运算符一起使用?例如:

string path;
//...
path += directory;
path += "/";
path += entry->d_name;
//etc.

使用 string 类可能效率稍低,但它会有额外的好处,可以帮助您避免缓冲区溢出问题和内存异常,例如您遇到的分段错误(我不是说string 将避免所有这些,但它会让你的生活更轻松)。

之前还有另一篇关于如何在 C++ 中构建目录字符串的文章:

c++ 如何从路径创建目录

Be careful using strcpy. It doesn't do bounds checking so even though path is only char[1], it's going to try to copy all of directory into it. That's probably your seg fault.

You have a lot of choices in terms of how to build up a string. Here's a long SO post on C++ string concatenation efficiency:

Efficient string concatenation in C++

If you're using C++, is there any reason you can't just use the built-in string library with the + operator? E.g.:

string path;
//...
path += directory;
path += "/";
path += entry->d_name;
//etc.

Using the string class might be slightly less efficient, but it will have the added benefit of helping you avoid buffer overflow issues and memory exceptions like the segmentation fault you're getting (I'm not saying string will avoid all of those, but it would make your life easier).

There's also been another previous SO post on how to build up a directory string in C++:

c++ how to create a directory from a path

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文