全国绿色计算大赛 模拟赛第一阶段 第2关:文件查看器

版权声明:博主的博客不值钱随便转载但要注明出处 https://blog.csdn.net/easylovecsdn/article/details/82990131

欺负我文件操作练的少,这道题文件操作非常简单,我开始的时候图省事用递归+递归参数写了一发,虽然用了不少时间但是感觉so easy啊,但是一想人家这是函数功能补全,我就开始想这个“+--”和“--”前面的空格数量怎么控制,改了一晚上,用一个静态变量就搞定了,看我下面的代码,至于文件操作,请参看博客https://blog.csdn.net/u010154760/article/details/45065457受益匪浅,感谢博主让我又学到不少东西。

void showDirStructure(char *folderPath)
{
    static int flor = 0;     //层数
 
    for (int i = 0; i < flor*2; i++) cout << " ";    //输出前置空格
 
    char buf[256];           //存放当前最高路径的文件夹名
    int len = 0;
    for (int i = strlen(folderPath)-1; folderPath[i] != '/'; i--) buf[len++] = folderPath[i];   //folderPath是完整的攀附路径,在此初步提取文件夹名
    buf[len] = '\0';
 
    for (int i = 0; i < len/2; i++) {                //初步提取出的名称是倒置的在此将他纠正
        char t = buf[i];
        buf[i] = buf[len-1-i];
        buf[len-1-i] = t;
    }
 
    cout << "+--" << buf << endl;                   //将文件夹名称输出
 
 
    DIR *dir = opendir(folderPath);
    struct dirent *i = NULL;
 
    while ((i = readdir(dir)) != NULL) {            //读取文件夹里的内容
 
        if (!strcmp(i->d_name, ".") || !strcmp(i->d_name, "..")) continue;     //读取出的内容包含.或..将其跳过
 
        strcpy(buf, folderPath);
        strcat(buf, "/");
        strcat(buf, i->d_name);                     //这3步string操作将完整的路径名称存放置buf中
 
        struct stat M;
        stat(buf, &M);
 
        if (S_ISDIR(M.st_mode))                     //判断文件类型是否为文件夹
        {
            flor += 1;
            showDirStructure(buf);
            flor -= 1;                              //这里运用到了回溯的思想
        }
        else
        {
 
            for (int i = 0; i < (flor+1)*2; i++) cout << " ";                   //若为文件则多输出两个空格然后输出文件名
 
            cout << "--" << i->d_name << endl;
        }
    }
 
    closedir(dir);
}

猜你喜欢

转载自blog.csdn.net/easylovecsdn/article/details/82990131