首页 > 解决方案 > strcpy 清除所有文件路径

问题描述

我正在尝试以这种方式将文件的名称和大小保存在目录中:

对于第一个文件,一切都很好。在第二个文件上,它说它无法确定文件路径。这是因为最后我清除了“mainPath”,但是当重新分配发生时,变量“path”也被清除了。

if ((directory = opendir(path)) != NULL)
{
    while((d = readdir(directory)) != NULL)
    {
        if(strcmp(d->d_name, "..")!=0 && strcmp(d->d_name, ".")!=0)
        {
            strcpy(fileSpec[i].fileName, d->d_name);
            char *mainPath = path;
            strcat(mainPath, d->d_name);

            fileSpec[i].fileSize = stat_filesize(mainPath);

            printf("\t%s ---> %ld\n", fileSpec[i].fileName, fileSpec[i].fileSize);
            i++;
            strcpy(mainPath, "");
        }
    }
    closedir(directory);
}

有一点我不明白。为什么当我strcpy(mainPath, "");只使用变量“mainPath”时没有清理?

这是因为我需要将路径作为参数传递。

标签: cstringdirectorypath

解决方案


推荐阅读