1

我正在对一个在基于 POSIX 的操作系统上遍历文件系统的程序进行单元测试,我无法找到一种方法来使用 NFTW 在没有一堆全局变量的情况下遍历它,所以我正在使用 dirent.h readdir( ) 的解决方案。为了测试递归的逻辑,我创建了这个函数,它向下递归一个目录,但以递归到第二个目录的段错误结束。

int recurse_dir(DIR *directory)
{
    struct dirent *direntry = readdir(directory);
    while(direntry != NULL)
    {
        struct stat file;
        lstat(direntry->d_name,&file);
        if(S_ISDIR(file.st_mode) && strcmp(direntry->d_name,".") != 0 && strcmp(direntry->d_name,"..") != 0)
        {
            printf("%s:\n",direntry->d_name);
            DIR *subdirectory;
            subdirectory = opendir(direntry->d_name);
            recurse_dir(subdirectory);
            closedir(subdirectory);
            printf("\n\n");
        }
        else
        {
            if(strcmp(direntry->d_name,".") != 0 && strcmp(direntry->d_name,"."))
            {
                printf("%s\n",direntry->d_name);
            }
        }
        direntry = readdir(directory);
    }
}

我用 gdb 对其进行了测试,发现手册页描述为当前文件名的空终止字符串的 d_name 变量填充了看起来像文件名的整个目录流与一堆空值和其他转义符混合的内容。我在下面发布一个示例。我是否误解了 d_name 变量的含义?

.gtkrc-2.0\000\000\bL\f@\000\000\000\000\000\303e0x\261\233-\a \000\b.kshrc\000\000\000\000\000\000\b)\000@\000\000\000\000\000Wa\340\315\366\310y\a\030\000\004src\000\004\037\000@\000\000\000\000\000\030\313\060\232\256\024\245\a \000\004Downloads\000\000\000\004\237\n@\000\000\000\000\000>5\321{\266-\004\t \000\004."...}

4

1 回答 1

0

You have not misunderstood. You are simply paying attention to data that isn't really meant for you. In C/C++, a null-terminated string is just that -- a null-terminated string. Characters in the buffer past the null could be anything, and are not intended to have any meaning for the consumer of the string.

You may see this phenomenon for a couple of common reasons:

  1. Collections of string literals are often stored in contiguous memory, separated by single null characters. If you just look at the memory, you'll see lots of strings.
  2. String buffers are typically only written out to the null. So if a fixed-size buffer contains a string that doesn't fill it completely, the excess bytes will still have whatever was written there before.
于 2021-10-11T15:49:19.460 回答