C++ 命令行文件管理小工具

本工具使用 C++ 编写,实现了一个简单的命令行文件管理界面,方便用户查看文件列表、进入子目录以及返回上级目录。

功能

  • 显示当前目录下的文件列表: 工具启动后会显示当前目录下的文件列表,以序号标注每个文件。
  • 进入子目录: 输入序号即可进入对应目录,并显示该目录下的文件列表。
  • 返回上级目录: 输入 0 可返回上级目录。

代码示例

#include <iostream>
#include <string>
#include <vector>
#include <dirent.h>

// 获取指定目录下的文件名列表
std::vector<std::string> getFilesInDirectory(const std::string& directory) {
    std::vector<std::string> files;
    DIR* dir;
    struct dirent* ent;
    if ((dir = opendir(directory.c_str())) != nullptr) {
        while ((ent = readdir(dir)) != nullptr) {
            std::string fileName = ent->d_name;
            if (fileName != '.' && fileName != '..') {
                files.push_back(fileName);
            }
        }
        closedir(dir);
    } else {
        std::cerr << '无法打开目录:' << directory << std::endl;
    }
    return files;
}

// 显示文件列表
void displayFileList(const std::vector<std::string>& files) {
    for (int i = 0; i < files.size(); ++i) {
        std::cout << i + 1 << '. ' << files[i] << std::endl;
    }
}

int main() {
    std::string currentDirectory = 'C:/'; // 初始目录为C盘
    std::string input;
    
    while (true) {
        std::cout << '当前目录:' << currentDirectory << std::endl;
        
        // 获取当前目录下的文件列表
        std::vector<std::string> files = getFilesInDirectory(currentDirectory);
        
        // 显示文件列表
        displayFileList(files);
        
        std::cout << '请输入序号(0返回上级目录):';
        std::cin >> input;
        
        int index = std::stoi(input);
        
        if (index == 0) {
            // 返回上级目录
            size_t found = currentDirectory.find_last_of('/\');
            if (found != std::string::npos) {
                currentDirectory = currentDirectory.substr(0, found);
            } else {
                std::cerr << '已经是根目录,无法返回上级目录。' << std::endl;
            }
        } else if (index > 0 && index <= files.size()) {
            // 打开子目录
            std::string selectedFile = files[index - 1];
            std::string newPath = currentDirectory + '/' + selectedFile;
            DIR* dir = opendir(newPath.c_str());
            if (dir != nullptr) {
                currentDirectory = newPath;
                closedir(dir);
            } else {
                std::cerr << '无法打开目录:' << newPath << std::endl;
            }
        } else {
            std::cerr << '无效的序号。' << std::endl;
        }
        
        std::cout << std::endl;
    }
    
    return 0;
}

编译

该代码可以在 gcc 4.9.2 编译器下编译,使用以下命令进行编译:

 g++ -o file_manager file_manager.cpp

注意事项

  • 该代码使用 dirent.h 头文件,该文件在一些旧版本的 C++ 标准中可能不被支持。如果遇到编译错误,请尝试使用更高版本的编译器或更新 C++ 标准。
  • 该代码仅提供简单的文件浏览功能,未实现文件操作功能(如创建、删除、复制等)。
  • 该代码只支持 Windows 系统,如果需要在其他操作系统上使用,需要修改代码中的文件路径分隔符等内容。

扩展

你可以根据自己的需求对该工具进行扩展,例如添加以下功能:

  • 添加文件操作功能,例如创建、删除、复制等。
  • 添加文件搜索功能,例如根据文件名或内容进行搜索。
  • 添加文件排序功能,例如按文件名或文件大小进行排序。
  • 添加用户界面,例如使用图形界面或 web 界面。

希望本工具能够帮助你更好地管理你的文件。


原文地址: https://www.cveoy.top/t/topic/phg4 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录