0

我有一个程序,它遍历目录结构并将路径中存在的文件连接到 szFile 。我在这里使用了 dirent 来获取目录条目。它仅在 SunOS 中的 for 循环内的 strcat 函数中转储核心。它在 HP 和 AIX 机器上运行良好。

#include <stdio.h>
#include <string.h>
#include <dirent.h>
#include <limits.h>
#include <sys/types.h>

int main()
{

    DIR            *pDirHand;

    char            szFile[1024];
    struct dirent   pdirent ;
    struct dirent *pResult = NULL;

    char *sDir = "fullpath"; /* fullpath can be /make/users/path */

    strncpy (szFile, sDir, sizeof(szFile)-1);
    szFile[sizeof(szFile)-1] = '\0';

    if (NULL == (pDirHand = opendir(szFile)))
    {
        return -1;
    }

    for(readdir_r(pDirHand, &pdirent, &pResult); pResult != 0;readdir_r(pDirHand, &pdirent, &pResult))
    {
        FILE *fp;
        fp=fopen("debug.log","a+");
        strcpy (szFile, sDir);

        strcat (szFile, "/");

        strcat (szFile, pdirent.d_name);
    }

    if (pDirHand) closedir (pDirHand);

    return 0;
}

我分配给 sDir 的路径中当前没有任何文件。它有“。” 和“..”目录条目,但我在该行中得到一个核心转储

strcat (szFile, pdirent.d_name);

我曾使用 dbx 找出 szFile 的值,在第二次迭代期间,该值超出了为其分配的内存。价值来自

“全路径/../全路径/../全路径/../全路径/../全路径/..全路径/..全路径/../../../../../../全路径/../fullpath/../fullpath/../fullpath/../fullpath/../fullpath/../fullpath/../fullpath/../fullpath/../fullpath/..fullpath/ ../fullpath/../fullpath/../fullpath/../fullpath/../fullpath/../fullpath/../fullpath/../fullpath/../fullpath/.." .. .

我试过使用 strlcat ,但 szFile 的连接值没有正确出现。有人在 SunOS 中遇到过这个问题或可以提供帮助吗?

4

0 回答 0