【app】遍历目录所有文件

遍历目录所有文件

 

原创,转载时请注明,谢谢。邮箱:tangzhongp@163.com

博客园地址:http://www.cnblogs.com/embedded-tzp

Csdn博客地址:http://blog.youkuaiyun.com/xiayulewa

   

Linux C : readdir

 

 

#include <stdio.h>

#include <dirent.h>

#include <stdlib.h>

 

int main(){

    DIR *dir_p = opendir("/");

    if(dir_p == NULL) perror("opendir"), exit(-1);

    struct dirent *ent;

    while(1){

        ent = readdir(dir_p);

        if(ent == NULL)  break;

        //打印子项类型和子项名

        if( 0 == strcmp(ent->d_name, ".")

         || 0 == strcmp(ent->d_name, "..")){

                continue;

        }   

        printf("%d, %s\n", ent->d_type, ent->d_name);

          //type == 4 是目录,其他是文件

    }

}

 

 

Linux C: scandir

 

 

#include <dirent.h>

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#include <unistd.h>

 

int dir_printall(const char *pathname)

{

    struct dirent **namelist = NULL;

    int ent_n;

    int i;

 

    ent_n = scandir(pathname, &namelist, NULL, alphasort);

    if (ent_n < 0){

        printf("scandir() fail : %s\n", pathname);

        return -1;

    }

    for(i = 0; i < ent_n; i++){

        if( 0 == strcmp(namelist[i]->d_name, ".")

                || 0 == strcmp(namelist[i]->d_name, "..")){ // skip parent dir and self

            continue;

        }

       

        char path_buf[512] = {0}; // use malloc will be bettor 

        sprintf(path_buf, "%s/%s", pathname, namelist[i]->d_name);

 

        printf("%s\n", path_buf);

 

        if(4 == namelist[i]->d_type){ // 4 means dir

            int retval = dir_printall( path_buf); // recurrence call

            if(-1 == retval){

                fprintf(stderr, "dir_printall() fail: %s\n", path_buf);

                continue;

                //goto out; // not end, for /proc/5236/net can't

            }

        }

    }

    

 

out:

    for(i = 0; i < ent_n; i++){

        if(namelist[i]){

            free(namelist[i]);

            namelist[i] = NULL;

        }

    }

    if(namelist){

        free(namelist);

        namelist = NULL;

    }

    return 0;

 

}

int main(void)

{

    if (-1 == dir_printall("/")){

        perror("dir_printall()");

    }

    return 0;

}

 

 

C++   

   

shell

     

#带完整路径

file=$(find ./)

echo $file

#只有文件名

file=$(ls -R)

echo $file

 

qt

自己做的项目中拷贝出来的一段简化的代码。

bool SearchThread::createDb()

{  

 qDebug() << __LINE__ << __FUNCTION__;

        QFileInfoList fileDriveList = QDir::drives(); // 获取盘符,windows下为c:, d:, e:, linux下为 /

        foreach(QFileInfo fileDrive, fileDriveList){ // 循环处理盘符

                qDebug() << fileDrive.absoluteFilePath();

                    createDb(fileDrive.absoluteFilePath());

        }   

        return true;

}

 

bool SearchThread::createDb(const QString &filePath)

{

        QDir dir = filePath;

 

   const QDir::Filters FILTERS =  QDir::AllDirs | QDir::Files | QDir::Drives

                              | QDir::NoDotAndDotDot | QDir::Hidden | QDir::System;

        QFileInfoList fileInfoList = dir.entryInfoList(FILTERS, QDir::DirsFirst | QDir::Name);

        foreach(QFileInfo fileInfo, fileInfoList){

                bool isdir = fileInfo.isDir();   

                if(isdir){

                        if(!fileInfo.isSymLink()){ // 不是链接文件,防止死循环

                            createDb(fileInfo.absoluteFilePath());

                        }

                }

        }

    return true;

}

 

### 使用 Electron 和 ADB API 遍历 Android 设备目录 为了实现这一目标,需要结合使用 Electron 构建前端界面,并利用 Node.js 的能力调用 ADB 命令来访问 Android 设备上的文件系统。具体来说: #### 安装依赖库 首先,在项目根目录安装必要的 npm 包以支持 ADB 功能: ```bash npm install adbkit --save ``` 此命令会下载 `adbkit` 库,该库提供了与 ADB 协议交互的功能[^1]。 #### 编写主进程代码 在 Electron 主进程中编写如下 JavaScript 代码用于连接至已授权的 Android 设备并获取其文件列表: ```javascript const {app, BrowserWindow} = require('electron'); const adb = require('adbkit'); let mainWindow; async function createWindow() { const client = adb.createClient(); try { let devices = await client.listDevices(); if (devices.length === 0) throw new Error("No device found"); // Select first connected device for simplicity. let deviceId = devices[0]; async function listFiles(path) { console.log(`Listing files under ${path}`); let entries = await client.shell(deviceId, ['ls', '-Rl', path]); return entries; } mainWindow.webContents.send('file-list', await listFiles('/sdcard')); } catch(error){ console.error(error.message); } } app.on('ready', () => { mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }); mainWindow.loadFile('index.html'); createWindow(); }); ``` 这段脚本实现了创建窗口、初始化 ADB 连接以及发送指令给选定设备列出指定路径下的所有文件及其子目录的内容[^2]。 #### 渲染页面接收数据展示 最后一步是在渲染进程中监听来自主进程的消息并将收到的数据呈现出来。可以在 HTML 文件内嵌入简单的 React 或 Vue 组件来进行更复杂的 UI 开发;这里仅给出基本的例子作为说明: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"/> <title>Electron + ADB File Explorer</title> <script type="text/javascript"> require('./renderer') </script> </head> <body> <div id="root"></div> <script src="./renderer.js"></script> </body> </html> ``` 对应的 renderer.js 中处理消息传递逻辑: ```javascript const {ipcRenderer} = require('electron'); document.addEventListener('DOMContentLoaded', () => { ipcRenderer.on('file-list', (_, arg) => { document.getElementById('root').innerText = arg; }); }) ``` 以上就是基于 Electron 结合 ADB 实现远程浏览 Android 设备存储空间的一个简单实例[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值