文件查看器

Linux上的文件操作是真的不会,C语言里静态变量的用法也不清楚,全是参考学长的博客,学到了好多https://blog.csdn.net/easylovecsdn/article/details/82990131

 

#include<stdio.h>
#include<iostream>
#include<string.h>
#include <sys/stat.h>
#include <dirent.h>
#define MAXSIZE 100
using namespace std;
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);               //相当于File 
    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);
}
int main() {
    showDirStructure("C:/Users/王教授/Desktop/dir");
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值